code stringlengths 1 1.72M | language stringclasses 1
value |
|---|---|
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
appName = "f3dinfo"
buildPath = buildDir()
binPath = join(buildPath, appName)
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.Append(LIBS = ["boost_program_options"])
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
mathInc = "SpiMathLib.h"
mathIncPaths = ["/usr/local64/openexr/1.4.0/include"]
mathLibs = ["Half", "Imath", "Iex"]
mathLibPaths = ["/usr/local64/openexr/1.4.0/lib64"]
incPaths = [
"/usr/local64/include/hdf5",
"/usr/local64/include/boost-1_34_1/"
]
libPaths = [
"/usr/local64/lib",
"/usr/local64/lib64",
"/usr/local64/lib/boost-1_34_1"
]
boostThreadLib = "boost_thread-gcc34-mt"
extraNamespace = "SPI"
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
from BuildSupport import *
# ------------------------------------------------------------------------------
buildPath = buildDir()
installPath = installDir()
sharedLibPath = join(buildPath, field3DName)
# ------------------------------------------------------------------------------
Import("env")
libEnv = env.Clone()
setupEnv(libEnv)
setupLibBuildEnv(libEnv)
libEnv.VariantDir(buildPath, src, duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
# Declare library
dyLib = libEnv.SharedLibrary(sharedLibPath, files)
stLib = libEnv.Library(sharedLibPath, files)
# Set up install area
headerDir = join(installPath, include, field3DName)
headerFiles = Glob(join(export, "*.h"))
headerFiles.remove(File(join(export, typesHeader)))
headerInstall = libEnv.Install(headerDir, headerFiles)
stLibInstall = libEnv.Install(join(installPath, "lib"), [stLib])
# Set up the dynamic library properly on OSX
dylibInstall = None
if sys.platform == "darwin":
dylibName = os.path.basename(str(dyLib[0]))
dylibInstallPath = os.path.abspath(join(installPath, "lib", dylibName))
# Create the builder
dylibEnv = env.Clone()
dylibBuilder = Builder(action = setDylibInternalPath,
suffix = ".dylib", src_suffix = ".dylib")
dylibEnv.Append(BUILDERS = {"SetDylibPath" : dylibBuilder})
# Call builder
dyLibInstall = dylibEnv.SetDylibPath(dylibInstallPath, dyLib)
else:
dyLibInstall = libEnv.Install(join(installPath, "lib"), [dyLib])
# Bake in math library in Types.h
bakeEnv = env.Clone()
bakeBuilder = Builder(action = bakeMathLibHeader,
suffix = ".h", src_suffix = ".h")
bakeEnv.Append(BUILDERS = {"BakeMathLibHeader" : bakeBuilder})
bakeTarget = bakeEnv.BakeMathLibHeader(join(headerDir, typesHeader),
join(export, typesHeader))
# Default targets ---
libEnv.Default(dyLib)
libEnv.Default(stLib)
libEnv.Default(headerInstall)
libEnv.Default(stLibInstall)
libEnv.Default(dyLibInstall)
bakeEnv.Default(bakeTarget)
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
from BuildSupport import *
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
# Contains various helper functions for the SCons build system
# ------------------------------------------------------------------------------
import os
import sys
from SCons.Script import *
from os.path import join
# ------------------------------------------------------------------------------
# Strings
# ------------------------------------------------------------------------------
field3DName = "Field3D"
buildDirPath = "build"
installDirPath = "install"
release = "release"
debug = "debug"
export = "export"
include = "include"
src = "src"
stdMathHeader = "StdMathLib.h"
siteFile = "Site.py"
typesHeader = "Types.h"
arch32 = "m32"
arch64 = "m64"
# ------------------------------------------------------------------------------
# Paths
# ------------------------------------------------------------------------------
systemIncludePaths = {
"darwin" : { arch32 : ["/usr/local/include",
"/opt/local/include"],
arch64 : ["/usr/local/include",
"/opt/local/include"]},
"linux2" : { arch32 : ["/usr/local/include"],
arch64 : ["/usr/local64/include"]}
}
systemLibPaths = {
"darwin" : { arch32 : ["/usr/local/lib",
"/opt/local/lib"],
arch64 : ["/usr/local/lib",
"/opt/local/lib"]},
"linux2" : { arch32 : ["/usr/local/lib"],
arch64 : ["/usr/local64/lib"]}
}
systemLibs = {
"darwin" : [],
"linux2" : ["dl"]
}
# ------------------------------------------------------------------------------
# Functions
# ------------------------------------------------------------------------------
def isDebugBuild():
return ARGUMENTS.get('debug', 0)
# ------------------------------------------------------------------------------
def architectureStr():
if ARGUMENTS.get('do64', 0):
return arch64
else:
return arch32
# ------------------------------------------------------------------------------
def buildDir():
basePath = join(buildDirPath, sys.platform, architectureStr())
if isDebugBuild():
return join(basePath, debug)
else:
return join(basePath, release)
# ------------------------------------------------------------------------------
def installDir():
basePath = join(installDirPath, sys.platform, architectureStr())
if isDebugBuild():
return join(basePath, debug)
else:
return join(basePath, release)
# ------------------------------------------------------------------------------
def getMathHeader():
if os.path.exists(siteFile):
import Site
if hasattr(Site, "mathInc"):
return Site.mathInc
return stdMathHeader
# ------------------------------------------------------------------------------
def setupLibBuildEnv(env, pathToRoot = "."):
# Project headers
env.Append(CPPPATH = [join(pathToRoot, export)])
# Check if Site.py exists
siteExists = False
if os.path.exists(join(pathToRoot, siteFile)):
sys.path.append(pathToRoot)
import Site
siteExists = True
if siteExists and \
hasattr(Site, "mathInc") and \
hasattr(Site, "mathIncPaths") and \
hasattr(Site, "mathLibs") and \
hasattr(Site, "mathLibPaths"):
mathIncStr = '\\"' + Site.mathInc + '\\"'
env.Append(CPPDEFINES =
{"FIELD3D_CUSTOM_MATH_LIB" : None})
env.Append(CPPDEFINES =
{"FIELD3D_MATH_LIB_INCLUDE" : mathIncStr})
# ------------------------------------------------------------------------------
def setupEnv(env, pathToRoot = "."):
baseIncludePaths = systemIncludePaths[sys.platform][architectureStr()]
baseLibPaths = systemLibPaths[sys.platform][architectureStr()]
baseLibs = systemLibs[sys.platform]
# System include paths
env.Append(CPPPATH = baseIncludePaths)
# System lib paths
env.Append(LIBPATH = baseLibPaths)
# System libs
env.Append(LIBS = baseLibs)
# Check if Site.py exists
siteExists = False
if os.path.exists(join(pathToRoot, siteFile)):
sys.path.append(pathToRoot)
import Site
siteExists = True
# Choose math library
if siteExists and \
hasattr(Site, "mathInc") and \
hasattr(Site, "mathIncPaths") and \
hasattr(Site, "mathLibs") and \
hasattr(Site, "mathLibPaths"):
env.Append(CPPPATH = Site.mathIncPaths)
env.Append(LIBS = Site.mathLibs)
env.Append(LIBPATH = Site.mathLibPaths)
env.Append(RPATH = Site.mathLibPaths)
else:
for path in baseIncludePaths:
env.Append(CPPPATH = join(path, "OpenEXR"))
env.Append(LIBS = ["Half"])
env.Append(LIBS = ["Iex"])
env.Append(LIBS = ["Imath"])
# Add in site-specific paths
if siteExists and hasattr(Site, "incPaths"):
env.AppendUnique(CPPPATH = Site.incPaths)
if siteExists and hasattr(Site, "libPaths"):
env.AppendUnique(LIBPATH = Site.libPaths)
env.AppendUnique(RPATH = Site.libPaths)
# Custom namespace
if siteExists and hasattr(Site, "extraNamespace"):
namespaceDict = {"FIELD3D_EXTRA_NAMESPACE" : Site.extraNamespace}
env.AppendUnique(CPPDEFINES = namespaceDict)
# System libs
env.Append(LIBS = ["z", "pthread"])
# Hdf5 lib
env.Append(LIBS = ["hdf5"])
# Boost threads
if siteExists and hasattr(Site, "boostThreadLib"):
env.Append(LIBS = [Site.boostThreadLib])
else:
env.Append(LIBS = ["boost_thread-mt"])
# Compile flags
if isDebugBuild():
env.Append(CCFLAGS = ["-g"])
else:
env.Append(CCFLAGS = ["-O3"])
env.Append(CCFLAGS = ["-Wall"])
# Set number of jobs to use
env.SetOption('num_jobs', numCPUs())
# 64 bit setup
if architectureStr() == arch64:
env.Append(CCFLAGS = ["-m64"])
env.Append(LINKFLAGS = ["-m64"])
else:
env.Append(CCFLAGS = ["-m32"])
env.Append(LINKFLAGS = ["-m32"])
# ------------------------------------------------------------------------------
def addField3DInstall(env, pathToRoot):
env.Prepend(CPPPATH = [join(pathToRoot, installDir(), "include")])
env.Prepend(LIBS = [field3DName])
env.Prepend(LIBPATH = [join(pathToRoot, installDir(), "lib")])
env.Prepend(RPATH = [join(pathToRoot, installDir(), "lib")])
# ------------------------------------------------------------------------------
def numCPUs():
if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
nCPUs = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(nCPUs, int) and nCPUs > 0:
return nCPUs
else:
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
if os.environ.has_key("NUMBER_OF_PROCESSORS"):
nCPUs = int(os.environ["NUMBER_OF_PROCESSORS"]);
if nCPUs > 0:
return nCPUs
return 1
# ------------------------------------------------------------------------------
def setDylibInternalPath(target, source, env):
# Copy the library file
srcName = str(source[0])
tgtName = str(target[0])
Execute(Copy(tgtName, srcName))
# Then run install_name_tool
cmd = "install_name_tool "
cmd += "-id " + os.path.abspath(tgtName) + " "
cmd += tgtName
print cmd
os.system(cmd)
# ------------------------------------------------------------------------------
def bakeMathLibHeader(target, source, env):
if len(target) != 1 or len(source) != 1:
print "Wrong number of arguments to bakeTypesIncludeFile"
return
out = open(str(target[0]), "w")
inFile = open(str(source[0]))
skip = False
for line in inFile.readlines():
if not skip and "#ifdef FIELD3D_CUSTOM_MATH_LIB" in line:
skip = True
newLine = '#include "' + getMathHeader() + '"\n'
out.writelines(newLine)
if not skip:
out.writelines(line)
if skip and "#endif" in line:
skip = False
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
mathInc = "SpiMathLib.h"
mathIncPaths = ["/usr/local64/openexr/1.4.0/include"]
mathLibs = ["Half", "Imath", "Iex"]
mathLibPaths = ["/usr/local64/openexr/1.4.0/lib64"]
incPaths = [
"/usr/local64/include/hdf5",
"/usr/local64/include/boost-1_34_1/"
]
libPaths = [
"/usr/local64/lib",
"/usr/local64/lib64",
"/usr/local64/lib/boost-1_34_1"
]
boostThreadLib = "boost_thread-gcc34-mt"
extraNamespace = "SPI"
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
from BuildSupport import *
# ------------------------------------------------------------------------------
buildPath = buildDir()
installPath = installDir()
sharedLibPath = join(buildPath, field3DName)
# ------------------------------------------------------------------------------
Import("env")
libEnv = env.Clone()
setupEnv(libEnv)
setupLibBuildEnv(libEnv)
libEnv.VariantDir(buildPath, src, duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
# Declare library
dyLib = libEnv.SharedLibrary(sharedLibPath, files)
stLib = libEnv.Library(sharedLibPath, files)
# Set up install area
headerDir = join(installPath, include, field3DName)
headerFiles = Glob(join(export, "*.h"))
headerFiles.remove(File(join(export, typesHeader)))
headerInstall = libEnv.Install(headerDir, headerFiles)
stLibInstall = libEnv.Install(join(installPath, "lib"), [stLib])
# Set up the dynamic library properly on OSX
dylibInstall = None
if sys.platform == "darwin":
dylibName = os.path.basename(str(dyLib[0]))
print str(dyLib), dylibName
dylibInstallPath = os.path.abspath(join(installPath, "lib", dylibName))
# Creat the builder
dylibEnv = env.Clone()
dylibBuilder = Builder(action = setDylibInternalPath,
suffix = ".dylib", src_suffix = ".dylib")
dylibEnv.Append(BUILDERS = {"SetDylibPath" : dylibBuilder})
# Call builder
dyLibInstall = dylibEnv.SetDylibPath(dylibInstallPath, dyLib)
else:
dyLibInstall = libEnv.Install(join(installPath, "lib"), [dyLib])
# Bake in math library in Types.h
bakeEnv = env.Clone()
bakeBuilder = Builder(action = bakeMathLibHeader,
suffix = ".h", src_suffix = ".h")
bakeEnv.Append(BUILDERS = {"BakeMathLibHeader" : bakeBuilder})
bakeTarget = bakeEnv.BakeMathLibHeader(join(headerDir, typesHeader),
join(export, typesHeader))
# Default targets ---
libEnv.Default(dyLib)
libEnv.Default(stLib)
libEnv.Default(headerInstall)
libEnv.Default(stLibInstall)
libEnv.Default(dyLibInstall)
bakeEnv.Default(bakeTarget)
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
from BuildSupport import *
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
# Contains various helper functions for the SCons build system
# ------------------------------------------------------------------------------
import os
import sys
from SCons.Script import *
from os.path import join
# ------------------------------------------------------------------------------
# Strings
# ------------------------------------------------------------------------------
field3DName = "Field3D"
buildDirPath = "build"
installDirPath = "install"
release = "release"
debug = "debug"
export = "export"
include = "include"
src = "src"
stdMathHeader = "StdMathLib.h"
siteFile = "Site.py"
typesHeader = "Types.h"
arch32 = "m32"
arch64 = "m64"
# ------------------------------------------------------------------------------
# Paths
# ------------------------------------------------------------------------------
systemIncludePaths = {
"darwin" : { arch32 : ["/usr/local/include",
"/opt/local/include"],
arch64 : ["/usr/local/include",
"/opt/local/include"]},
"linux2" : { arch32 : ["/usr/local/include"],
arch64 : ["/usr/local64/include"]}
}
systemLibPaths = {
"darwin" : { arch32 : ["/usr/local/lib",
"/opt/local/lib"],
arch64 : ["/usr/local/lib",
"/opt/local/lib"]},
"linux2" : { arch32 : ["/usr/local/lib"],
arch64 : ["/usr/local64/lib"]}
}
systemLibs = {
"darwin" : [],
"linux2" : ["dl"]
}
# ------------------------------------------------------------------------------
# Functions
# ------------------------------------------------------------------------------
def isDebugBuild():
return ARGUMENTS.get('debug', 0)
# ------------------------------------------------------------------------------
def architectureStr():
if ARGUMENTS.get('do64', 0):
return arch64
else:
return arch32
# ------------------------------------------------------------------------------
def buildDir():
basePath = join(buildDirPath, sys.platform, architectureStr())
if isDebugBuild():
return join(basePath, debug)
else:
return join(basePath, release)
# ------------------------------------------------------------------------------
def installDir():
basePath = join(installDirPath, sys.platform, architectureStr())
if isDebugBuild():
return join(basePath, debug)
else:
return join(basePath, release)
# ------------------------------------------------------------------------------
def getMathHeader():
if os.path.exists(siteFile):
import Site
if hasattr(Site, "mathInc"):
return Site.mathInc
return stdMathHeader
# ------------------------------------------------------------------------------
def setupLibBuildEnv(env, pathToRoot = "."):
# Project headers
env.Append(CPPPATH = [join(pathToRoot, export)])
# Check if Site.py exists
siteExists = False
if os.path.exists(join(pathToRoot, siteFile)):
sys.path.append(pathToRoot)
import Site
siteExists = True
if siteExists and \
hasattr(Site, "mathInc") and \
hasattr(Site, "mathIncPaths") and \
hasattr(Site, "mathLibs") and \
hasattr(Site, "mathLibPaths"):
mathIncStr = '\\"' + Site.mathInc + '\\"'
env.Append(CPPDEFINES =
{"FIELD3D_CUSTOM_MATH_LIB" : None})
env.Append(CPPDEFINES =
{"FIELD3D_MATH_LIB_INCLUDE" : mathIncStr})
# ------------------------------------------------------------------------------
def setupEnv(env, pathToRoot = "."):
baseIncludePaths = systemIncludePaths[sys.platform][architectureStr()]
baseLibPaths = systemLibPaths[sys.platform][architectureStr()]
baseLibs = systemLibs[sys.platform]
# System include paths
env.Append(CPPPATH = baseIncludePaths)
# System lib paths
env.Append(LIBPATH = baseLibPaths)
# System libs
env.Append(LIBS = baseLibs)
# Check if Site.py exists
siteExists = False
if os.path.exists(join(pathToRoot, siteFile)):
sys.path.append(pathToRoot)
import Site
siteExists = True
# Choose math library
if siteExists and \
hasattr(Site, "mathInc") and \
hasattr(Site, "mathIncPaths") and \
hasattr(Site, "mathLibs") and \
hasattr(Site, "mathLibPaths"):
env.Append(CPPPATH = Site.mathIncPaths)
env.Append(LIBS = Site.mathLibs)
env.Append(LIBPATH = Site.mathLibPaths)
env.Append(RPATH = Site.mathLibPaths)
else:
for path in baseIncludePaths:
env.Append(CPPPATH = join(path, "OpenEXR"))
env.Append(LIBS = ["Half"])
env.Append(LIBS = ["Iex"])
env.Append(LIBS = ["Imath"])
# Add in site-specific paths
if siteExists and hasattr(Site, "incPaths"):
env.AppendUnique(CPPPATH = Site.incPaths)
if siteExists and hasattr(Site, "libPaths"):
env.AppendUnique(LIBPATH = Site.libPaths)
env.AppendUnique(RPATH = Site.libPaths)
# Custom namespace
if siteExists and hasattr(Site, "extraNamespace"):
namespaceDict = {"FIELD3D_EXTRA_NAMESPACE" : Site.extraNamespace}
env.AppendUnique(CPPDEFINES = namespaceDict)
# System libs
env.Append(LIBS = ["z", "pthread"])
# Hdf5 lib
env.Append(LIBS = ["hdf5"])
# Boost threads
if siteExists and hasattr(Site, "boostThreadLib"):
env.Append(LIBS = [Site.boostThreadLib])
else:
env.Append(LIBS = ["boost_thread-mt"])
# Compile flags
if isDebugBuild():
env.Append(CCFLAGS = ["-g"])
else:
env.Append(CCFLAGS = ["-O3"])
env.Append(CCFLAGS = ["-Wall"])
# Set number of jobs to use
env.SetOption('num_jobs', numCPUs())
# 64 bit setup
if architectureStr() == arch64:
env.Append(CCFLAGS = ["-m64"])
env.Append(LINKFLAGS = ["-m64"])
else:
env.Append(CCFLAGS = ["-m32"])
env.Append(LINKFLAGS = ["-m32"])
# ------------------------------------------------------------------------------
def addField3DInstall(env, pathToRoot):
env.Append(CPPPATH = [join(pathToRoot, installDir(), "include")])
env.Append(LIBS = [field3DName])
env.Append(LIBPATH = [join(pathToRoot, installDir(), "lib")])
env.Append(RPATH = [join(pathToRoot, installDir(), "lib")])
# ------------------------------------------------------------------------------
def numCPUs():
if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
nCPUs = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(nCPUs, int) and nCPUs > 0:
return nCPUs
else:
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
if os.environ.has_key("NUMBER_OF_PROCESSORS"):
nCPUs = int(os.environ["NUMBER_OF_PROCESSORS"]);
if nCPUs > 0:
return nCPUs
return 1
# ------------------------------------------------------------------------------
def setDylibInternalPath(target, source, env):
# Copy the library file
srcName = str(source[0])
tgtName = str(target[0])
Execute(Copy(tgtName, srcName))
# Then run install_name_tool
cmd = "install_name_tool "
cmd += "-id " + os.path.abspath(tgtName) + " "
cmd += tgtName
print cmd
os.system(cmd)
# ------------------------------------------------------------------------------
def bakeMathLibHeader(target, source, env):
if len(target) != 1 or len(source) != 1:
print "Wrong number of arguments to bakeTypesIncludeFile"
return
out = open(str(target[0]), "w")
inFile = open(str(source[0]))
skip = False
for line in inFile.readlines():
if not skip and "#ifdef FIELD3D_CUSTOM_MATH_LIB" in line:
skip = True
newLine = '#include "' + getMathHeader() + '"\n'
out.writelines(newLine)
if not skip:
out.writelines(line)
if skip and "#endif" in line:
skip = False
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../../.."
sys.path.append(pathToRoot)
from BuildSupport import *
buildPath = buildDir()
binPath = join(buildPath, os.path.basename(os.getcwd()))
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
appName = "f3dinfo"
buildPath = buildDir()
binPath = join(buildPath, appName)
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.Append(LIBS = ["boost_program_options"])
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
import os
import sys
# ------------------------------------------------------------------------------
pathToRoot = "../.."
sys.path.append(pathToRoot)
from BuildSupport import *
appName = "f3dsample"
buildPath = buildDir()
binPath = join(buildPath, appName)
# ------------------------------------------------------------------------------
Import("env")
appEnv = env.Clone()
setupEnv(appEnv, pathToRoot)
addField3DInstall(appEnv, pathToRoot)
appEnv.Append(LIBS = ["boost_program_options"])
appEnv.VariantDir(buildPath, ".", duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
app = appEnv.Program(binPath, files)
appEnv.Default(app)
# ------------------------------------------------------------------------------
| Python |
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
mathInc = "SpiMathLib.h"
mathIncPaths = ["/usr/local64/openexr/1.4.0/include"]
mathLibs = ["Half", "Imath", "Iex"]
mathLibPaths = ["/usr/local64/openexr/1.4.0/lib64"]
incPaths = [
"/usr/local64/include/hdf5",
"/usr/local64/include/boost-1_34_1/"
]
libPaths = [
"/usr/local64/lib",
"/usr/local64/lib64",
"/usr/local64/lib/boost-1_34_1"
]
boostThreadLib = "boost_thread-gcc34-mt"
extraNamespace = "SPI"
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
from BuildSupport import *
# ------------------------------------------------------------------------------
buildPath = buildDir()
installPath = installDir()
sharedLibPath = join(buildPath, field3DName)
# ------------------------------------------------------------------------------
Import("env")
libEnv = env.Clone()
setupEnv(libEnv)
setupLibBuildEnv(libEnv)
libEnv.VariantDir(buildPath, src, duplicate = 0)
files = Glob(join(buildPath, "*.cpp"))
# Declare library
dyLib = libEnv.SharedLibrary(sharedLibPath, files)
stLib = libEnv.Library(sharedLibPath, files)
# Set up install area
headerDir = join(installPath, include, field3DName)
headerFiles = Glob(join(export, "*.h"))
headerFiles.remove(File(join(export, typesHeader)))
headerInstall = libEnv.Install(headerDir, headerFiles)
stLibInstall = libEnv.Install(join(installPath, "lib"), [stLib])
# Set up the dynamic library properly on OSX
dylibInstall = None
if sys.platform == "darwin":
dylibName = os.path.basename(str(dyLib[0]))
dylibInstallPath = os.path.abspath(join(installPath, "lib", dylibName))
# Create the builder
dylibEnv = env.Clone()
dylibBuilder = Builder(action = setDylibInternalPath,
suffix = ".dylib", src_suffix = ".dylib")
dylibEnv.Append(BUILDERS = {"SetDylibPath" : dylibBuilder})
# Call builder
dyLibInstall = dylibEnv.SetDylibPath(dylibInstallPath, dyLib)
else:
dyLibInstall = libEnv.Install(join(installPath, "lib"), [dyLib])
# Bake in math library in Types.h
bakeEnv = env.Clone()
bakeBuilder = Builder(action = bakeMathLibHeader,
suffix = ".h", src_suffix = ".h")
bakeEnv.Append(BUILDERS = {"BakeMathLibHeader" : bakeBuilder})
bakeTarget = bakeEnv.BakeMathLibHeader(join(headerDir, typesHeader),
join(export, typesHeader))
# Default targets ---
libEnv.Default(dyLib)
libEnv.Default(stLib)
libEnv.Default(headerInstall)
libEnv.Default(stLibInstall)
libEnv.Default(dyLibInstall)
bakeEnv.Default(bakeTarget)
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
from BuildSupport import *
# ------------------------------------------------------------------------------
env = Environment()
Export("env")
SConscript("SConscript")
# ------------------------------------------------------------------------------
| Python |
#
# Copyright (c) 2009 Sony Pictures Imageworks Inc.
#
# All rights reserved.
#
# 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 Sony Pictures Imageworks 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 OWNER 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.
# ------------------------------------------------------------------------------
# Contains various helper functions for the SCons build system
# ------------------------------------------------------------------------------
import os
import sys
from SCons.Script import *
from os.path import join
# ------------------------------------------------------------------------------
# Strings
# ------------------------------------------------------------------------------
field3DName = "Field3D"
buildDirPath = "build"
installDirPath = "install"
release = "release"
debug = "debug"
export = "export"
include = "include"
src = "src"
stdMathHeader = "StdMathLib.h"
siteFile = "Site.py"
typesHeader = "Types.h"
arch32 = "m32"
arch64 = "m64"
# ------------------------------------------------------------------------------
# Paths
# ------------------------------------------------------------------------------
systemIncludePaths = {
"darwin" : { arch32 : ["/usr/local/include",
"/opt/local/include"],
arch64 : ["/usr/local/include",
"/opt/local/include"]},
"linux2" : { arch32 : ["/usr/local/include"],
arch64 : ["/usr/local64/include"]}
}
systemLibPaths = {
"darwin" : { arch32 : ["/usr/local/lib",
"/opt/local/lib"],
arch64 : ["/usr/local/lib",
"/opt/local/lib"]},
"linux2" : { arch32 : ["/usr/local/lib"],
arch64 : ["/usr/local64/lib"]}
}
systemLibs = {
"darwin" : [],
"linux2" : ["dl"]
}
# ------------------------------------------------------------------------------
# Functions
# ------------------------------------------------------------------------------
def isDebugBuild():
return ARGUMENTS.get('debug', 0)
# ------------------------------------------------------------------------------
def architectureStr():
if ARGUMENTS.get('do64', 0):
return arch64
else:
return arch32
# ------------------------------------------------------------------------------
def buildDir():
basePath = join(buildDirPath, sys.platform, architectureStr())
if isDebugBuild():
return join(basePath, debug)
else:
return join(basePath, release)
# ------------------------------------------------------------------------------
def installDir():
basePath = join(installDirPath, sys.platform, architectureStr())
if isDebugBuild():
return join(basePath, debug)
else:
return join(basePath, release)
# ------------------------------------------------------------------------------
def getMathHeader():
if os.path.exists(siteFile):
import Site
if hasattr(Site, "mathInc"):
return Site.mathInc
return stdMathHeader
# ------------------------------------------------------------------------------
def setupLibBuildEnv(env, pathToRoot = "."):
# Project headers
env.Append(CPPPATH = [join(pathToRoot, export)])
# Check if Site.py exists
siteExists = False
if os.path.exists(join(pathToRoot, siteFile)):
sys.path.append(pathToRoot)
import Site
siteExists = True
if siteExists and \
hasattr(Site, "mathInc") and \
hasattr(Site, "mathIncPaths") and \
hasattr(Site, "mathLibs") and \
hasattr(Site, "mathLibPaths"):
mathIncStr = '\\"' + Site.mathInc + '\\"'
env.Append(CPPDEFINES =
{"FIELD3D_CUSTOM_MATH_LIB" : None})
env.Append(CPPDEFINES =
{"FIELD3D_MATH_LIB_INCLUDE" : mathIncStr})
# ------------------------------------------------------------------------------
def setupEnv(env, pathToRoot = "."):
baseIncludePaths = systemIncludePaths[sys.platform][architectureStr()]
baseLibPaths = systemLibPaths[sys.platform][architectureStr()]
baseLibs = systemLibs[sys.platform]
# System include paths
env.Append(CPPPATH = baseIncludePaths)
# System lib paths
env.Append(LIBPATH = baseLibPaths)
# System libs
env.Append(LIBS = baseLibs)
# Check if Site.py exists
siteExists = False
if os.path.exists(join(pathToRoot, siteFile)):
sys.path.append(pathToRoot)
import Site
siteExists = True
# Choose math library
if siteExists and \
hasattr(Site, "mathInc") and \
hasattr(Site, "mathIncPaths") and \
hasattr(Site, "mathLibs") and \
hasattr(Site, "mathLibPaths"):
env.Append(CPPPATH = Site.mathIncPaths)
env.Append(LIBS = Site.mathLibs)
env.Append(LIBPATH = Site.mathLibPaths)
env.Append(RPATH = Site.mathLibPaths)
else:
for path in baseIncludePaths:
env.Append(CPPPATH = join(path, "OpenEXR"))
env.Append(LIBS = ["Half"])
env.Append(LIBS = ["Iex"])
env.Append(LIBS = ["Imath"])
# Add in site-specific paths
if siteExists and hasattr(Site, "incPaths"):
env.AppendUnique(CPPPATH = Site.incPaths)
if siteExists and hasattr(Site, "libPaths"):
env.AppendUnique(LIBPATH = Site.libPaths)
env.AppendUnique(RPATH = Site.libPaths)
# Custom namespace
if siteExists and hasattr(Site, "extraNamespace"):
namespaceDict = {"FIELD3D_EXTRA_NAMESPACE" : Site.extraNamespace}
env.AppendUnique(CPPDEFINES = namespaceDict)
# System libs
env.Append(LIBS = ["z", "pthread"])
# Hdf5 lib
env.Append(LIBS = ["hdf5"])
# Boost threads
if siteExists and hasattr(Site, "boostThreadLib"):
env.Append(LIBS = [Site.boostThreadLib])
else:
env.Append(LIBS = ["boost_thread-mt"])
# Compile flags
if isDebugBuild():
env.Append(CCFLAGS = ["-g"])
else:
env.Append(CCFLAGS = ["-O3"])
env.Append(CCFLAGS = ["-Wall"])
# Set number of jobs to use
env.SetOption('num_jobs', numCPUs())
# 64 bit setup
if architectureStr() == arch64:
env.Append(CCFLAGS = ["-m64"])
env.Append(LINKFLAGS = ["-m64"])
else:
env.Append(CCFLAGS = ["-m32"])
env.Append(LINKFLAGS = ["-m32"])
# ------------------------------------------------------------------------------
def addField3DInstall(env, pathToRoot):
env.Prepend(CPPPATH = [join(pathToRoot, installDir(), "include")])
env.Prepend(LIBS = [field3DName])
env.Prepend(LIBPATH = [join(pathToRoot, installDir(), "lib")])
env.Prepend(RPATH = [join(pathToRoot, installDir(), "lib")])
# ------------------------------------------------------------------------------
def numCPUs():
if os.sysconf_names.has_key("SC_NPROCESSORS_ONLN"):
nCPUs = os.sysconf("SC_NPROCESSORS_ONLN")
if isinstance(nCPUs, int) and nCPUs > 0:
return nCPUs
else:
return int(os.popen2("sysctl -n hw.ncpu")[1].read())
if os.environ.has_key("NUMBER_OF_PROCESSORS"):
nCPUs = int(os.environ["NUMBER_OF_PROCESSORS"]);
if nCPUs > 0:
return nCPUs
return 1
# ------------------------------------------------------------------------------
def setDylibInternalPath(target, source, env):
# Copy the library file
srcName = str(source[0])
tgtName = str(target[0])
Execute(Copy(tgtName, srcName))
# Then run install_name_tool
cmd = "install_name_tool "
cmd += "-id " + os.path.abspath(tgtName) + " "
cmd += tgtName
print cmd
os.system(cmd)
# ------------------------------------------------------------------------------
def bakeMathLibHeader(target, source, env):
if len(target) != 1 or len(source) != 1:
print "Wrong number of arguments to bakeTypesIncludeFile"
return
out = open(str(target[0]), "w")
inFile = open(str(source[0]))
skip = False
for line in inFile.readlines():
if not skip and "#ifdef FIELD3D_CUSTOM_MATH_LIB" in line:
skip = True
newLine = '#include "' + getMathHeader() + '"\n'
out.writelines(newLine)
if not skip:
out.writelines(line)
if skip and "#endif" in line:
skip = False
# ------------------------------------------------------------------------------
| Python |
import math
import time
def wrap( l ):
return [ ( l[i], l[ ( i + 1 ) % len(l) ] ) for i in range( len( l ) ) ]
class Vec2:
def __init__( self, x = 0, y = 0 ):
self.x = float( x )
self.y = float( y )
def __repr__( self ):
return 'Vec2( %.2f, %.2f )' % ( self.x, self.y )
def __eq__( self, v, eps = 1e-5 ):
return abs( self.x - v.x ) < eps and abs( self.y - v.y ) < eps
def __neg__( self ):
return Vec2( -self.x, -self.y )
def __add__( self, v ):
return Vec2( self.x + v.x, self.y + v.y )
def __sub__( self, v ):
return Vec2( self.x - v.x, self.y - v.y )
def __mul__( self, v ):
if isinstance( v, Vec2 ):
return Vec2( self.x * v.x, self.y * v.y )
else:
return Vec2( self.x * v, self.y * v )
def __div__( self, v ):
if isinstance( v, Vec2 ):
return Vec2( self.x / v.x, self.y / v.y )
else:
return Vec2( self.x / v, self.y / v )
def squaredLength( self ):
return self.x * self.x + self.y * self.y
def length( self ):
return math.sqrt( self.squaredLength() )
def normalize( self ):
return self / self.length()
def dot( self, v ):
return self.x * v.x + self.y * v.y
def project( self, v ):
return v * ( self.dot( v ) / v.squaredLength() )
def cross( self, v ):
return self.x * v.y - self.y * v.x
def perp( self ):
return Vec2( -self.y, self.x )
@staticmethod
def distToLine( a, b, p ):
return ( p - a ).cross( b - a ) / ( b - a ).length()
class PointMass:
def __init__( self, pos, mass, gravity = Vec2( 0, -5 ), maxVel = 5 ):
self.pos = pos
self.mass = mass
self.gravity = gravity
self.maxVel = maxVel
self.vel = Vec2()
self.force = Vec2()
def __repr__( self ):
return 'PointMass( %s, %.2f )' % ( self.pos, self.mass )
def applyForce( self, f ):
self.force += f
def update( self, dt ):
if self.mass > 0:
self.vel += ( self.force / self.mass + self.gravity ) * dt
if self.vel.length() > self.maxVel:
self.vel = self.vel.normalize() * min( self.vel.length(), self.maxVel )
self.pos += self.vel * dt
self.force = Vec2()
class Spring:
def __init__( self, p1, p2, p, d ):
self.p1 = p1
self.p2 = p2
self.p = p
self.d = d
self.l = ( self.p1.pos - self.p2.pos ).length()
def __repr__( self ):
return 'Spring( %.2f )' % ( ( self.p1.pos - self.p2.pos ).length() / self.l )
def update( self, dt ):
diff = self.p2.pos - self.p1.pos
normDiff = diff.normalize()
pf = normDiff * ( ( diff.length() - self.l ) / self.l * self.p )
df = ( self.p1.vel - self.p2.vel ).project( normDiff ) * -self.d
f = pf + df
self.p1.applyForce( f )
self.p2.applyForce( -f )
class Body:
DEFAULT_P = 100
DEFAULT_D = 1
DEFAULT_FRICTION = 0.1
def __init__( self, pointMasses, springs, tris, p = DEFAULT_P, d = DEFAULT_D, friction = DEFAULT_FRICTION ):
self.pointMasses = pointMasses
self.p = p
self.d = d
self.friction = friction
if springs:
self.springs = springs
else:
self.springs = []
for i in range( len( self.pointMasses ) ):
for j in range( i + 1, len( self.pointMasses ) ):
self.springs.append( Spring( self.pointMasses[i], self.pointMasses[j], p, d ) )
self.tris = tris or []
@staticmethod
def circle( pos, r, n = 8, m = 1, p = DEFAULT_P, d = DEFAULT_D ):
pm = m / ( n + 1. )
center = PointMass( pos, pm )
points = []
for i in range( n ):
th = float( i ) / float( n ) * math.pi * 2
points.append( PointMass( pos + Vec2( r * math.cos( th ), r * math.sin( th ) ), pm ) )
springs = []
tris = []
for i in range( n ):
springs.append( Spring( points[i], points[ ( i + 1 ) % n ], p, d ) )
springs.append( Spring( points[i], center, p, d ) )
tris.append( ( 0, ( i + 1 ) % n + 1, i + 1 ) )
return Body( [ center ] + points, springs, tris )
@staticmethod
def rectangle( min, max, m = 1, p = DEFAULT_P, d = DEFAULT_D ):
ds = [ Vec2( 0, 0 ), Vec2( 0, 1 ), Vec2( 1, 1 ), Vec2( 1, 0 ) ]
points = [ PointMass( min + ( max - min ) * dv, m / 4. ) for dv in ds ]
return Body( points, None, [ (0,1,2), (0,2,3) ], p = p, d = d )
def getEdges( self ):
return sum( map( wrap, self.tris ), [] )
def getPerimeter( self ):
def edgesEqual( e1, e2 ):
return ( e1[0] == e2[0] and e1[1] == e2[1] ) or ( e1[0] == e2[1] and e1[1] == e2[0] )
def edgeInList( e1, l ):
return any( [ edgesEqual( e1, e2 ) for e2 in l ] )
perimeter = []
edges = self.getEdges()
for i, e in enumerate( edges ):
if not edgeInList( e, edges[:i] ) and not edgeInList( e, edges[i+1:] ):
perimeter.append( e )
return perimeter
def getBoundingBox( self ):
x = [ pm.pos.x for pm in self.pointMasses ]
y = [ pm.pos.y for pm in self.pointMasses ]
return Vec2( min( x ), min( y ) ), Vec2( max( x ), max( y ) )
def getCenter( self ):
return sum( [ pm.pos for pm in self.pointMasses ], Vec2() ) / len( self.pointMasses )
def getBoundingCircle( self ):
c = self.getCenter()
return c, max( [ ( pm.pos - c ).length() for pm in self.pointMasses ] )
def update( self, dt ):
for spring in self.springs:
spring.update( dt )
for pointMass in self.pointMasses:
pointMass.update( dt )
def inside( self, p ):
posList = [ pm.pos for pm in self.pointMasses ]
for tri in self.tris:
dists = [ Vec2.distToLine( posList[i], posList[j], p ) for i, j in wrap( tri ) ]
prods = [ i * j for i, j in wrap( dists ) ]
if all( [ prod >= 0 for prod in prods ] ):
return True
return False
def offsetTo( self, p, dir = None ):
if self.inside( p ):
offsets = []
for edge1, edge2 in self.getPerimeter():
p1 = self.pointMasses[ edge1 ]
p2 = self.pointMasses[ edge2 ]
a = p1.pos
b = p2.pos
d = Vec2.distToLine( a, b, p )
offset = ( b - a ).normalize().perp() * d
if d > 0 and ( not dir or dir.dot( offset ) > 0 ):
offsets.append( ( offset, ( p1, p2 ) ) )
return offsets and min( offsets, key = lambda offset: offset[0].length() )
def collide( self, body ):
for pm in self.pointMasses:
res = body.offsetTo( pm.pos, self.getCenter() - body.getCenter() )
if res:
offset, points = res
surfaceVel = sum( [ p.vel for p in points ], Vec2() ) / float( len( points ) )
relVel = pm.vel - surfaceVel
projVel = relVel.project( offset )
offsetf = offset * self.p - projVel * self.d
perpOffset = offset.perp()
perpVel = relVel.project( perpOffset )
frictionf = perpVel * -body.friction
f = offsetf + frictionf
pm.applyForce( f )
for point in points:
point.applyForce( f / float( -len( points ) ) )
def overlaps( self, body ):
return any( [ self.offsetTo( pm.pos ) for pm in body.pointMasses ] ) or any( [ body.offsetTo( pm.pos ) for pm in self.pointMasses ] )
def applyForce( self, f ):
df = f / float( len( self.pointMasses ) )
for pm in self.pointMasses:
pm.applyForce( df )
@staticmethod
def test():
r = Body.rectangle( Vec2(), Vec2( 1, 1 ) )
assert not r.offsetTo( Vec2( 1.5, 0.5 ) )
assert Vec2( -0.1, 0 ) == r.offsetTo( Vec2( 0.1, 0.5 ) )[0]
assert Vec2( 0, 0.1 ) == r.offsetTo( Vec2( 0.5, 0.9 ) )[0]
assert Vec2( 0, -0.1 ) == r.offsetTo( Vec2( 0.2, 0.1 ) )[0]
c = Body.circle( Vec2( 0, 0 ), 1 )
assert c.offsetTo( Vec2( 0, 0 ) )
assert not c.offsetTo( Vec2( -1, -1 ) )
assert not c.offsetTo( Vec2( 1, -1 ) )
assert not c.offsetTo( Vec2( -1, 1 ) )
assert not c.offsetTo( Vec2( 1, 1 ) )
class World:
def __init__( self, bodies ):
self.bodies = bodies or []
def run( self, maxTime = -1, mindt = 0.01 ):
start = last = time.time()
self.shutdown = False
while not self.shutdown and ( maxTime < 0 or last - start < maxTime ):
now = time.time()
dt = now - last
t = now - start
if mindt < 0 or dt > mindt:
last += dt
for i, body1 in enumerate( self.bodies ):
for j, body2 in enumerate( self.bodies ):
if i != j:
body1.collide( body2 )
body1.update( dt )
print '%.2f' % t, [ body.getCenter() for body in self.bodies ]
if __name__ == '__main__':
Body.test()
objects = []
objects += [ Body.rectangle( Vec2( -100, -10 ), Vec2( 100, 0 ), -1 ) ]
objects += [ Body.circle( Vec2( i * 0.5, 5 + i * 1.5 ), 0.5, 8 ) for i in range( 3 ) ]
for object in objects[1:]:
object.applyForce( Vec2( -100, 0 ) )
World( objects ).run()
| Python |
import random
from copy import copy
import math
import time
class GA:
ROULETTE = 'ROULETTE'
TOURNAMENT = 'TOURNAMENT'
class Param:
BOOL = 'BOOL'
INT = 'INT'
FLOAT = 'FLOAT'
ENUM = 'ENUM'
FLOAT_LIST = 'FLOAT_LIST'
INT_LIST = 'INT_LIST'
def __init__( self, name, type, size, **kwargs ):
self.name = name
self.type = type
self.size = size
self.__dict__.update( kwargs )
@staticmethod
def bool( name ):
return GA.Param( name, GA.Param.BOOL, 1 )
@staticmethod
def int( name, min, max ):
return GA.Param( name, GA.Param.INT, GA.Param.bitsForInt( max - min ), min = min, max = max )
@staticmethod
def float( name, min, max, acc ):
steps = int( math.ceil( ( max - min ) / acc ) )
return GA.Param( name, GA.Param.FLOAT, GA.Param.bitsForInt( steps ), min = min, max = max )
@staticmethod
def enum( name, vals ):
return GA.Param( name, GA.Param.ENUM, GA.Param.bitsForInt( len( vals ) ), vals = vals )
@staticmethod
def floatList( name, min, max, acc, num ):
steps = int( math.ceil( ( max - min ) / acc ) )
numBits = GA.Param.bitsForInt( steps )
return GA.Param( name, GA.Param.FLOAT_LIST, numBits * num, min = min, max = max, num = num, numBits = numBits )
@staticmethod
def intList( name, min, max, num ):
numBits = GA.Param.bitsForInt( max - min )
return GA.Param( name, GA.Param.INT_LIST, numBits * num, min = min, max = max, num = num, numBits = numBits )
@staticmethod
def bitsForInt( i ):
return int( math.ceil( math.log( i, 2 ) ) )
@staticmethod
def decodeInt( bits ):
return sum( [ 2 ** i * b for i, b in enumerate( bits ) ] )
@staticmethod
def decodeFloat( min, max, bits ):
return min + ( max - min ) * GA.Param.decodeInt( bits ) / float( 2 ** len( bits ) - 1 )
def decode( self, bits ):
if self.type == GA.Param.BOOL:
return bits[0]
elif self.type == GA.Param.INT:
return self.min + GA.Param.decodeInt( bits ) % ( self.max - self.min + 1 )
elif self.type == GA.Param.FLOAT:
return GA.Param.decodeFloat( self.min, self.max, bits )
elif self.type == GA.Param.ENUM:
return self.vals[ GA.Param.decodeInt( bits ) % len( self.vals ) ]
elif self.type == GA.Param.FLOAT_LIST:
return [ GA.Param.decodeFloat( self.min, self.max, bits[ i: i + self.numBits ] ) for i in range( len( bits ) )[::self.numBits] ]
elif self.type == GA.Param.INT_LIST:
return [ self.min + GA.Param.decodeInt( bits[ i: i + self.numBits ] ) % ( self.max - self.min + 1 ) for i in range( len( bits ) )[::self.numBits] ]
else:
raise NotImplemented
def __init__( self, params, eval, popSize = 1000, numGens = None, maxTime = None, crossProb = 0.25, mutateProb = 0.01, selectionMethod = None, verbose = False ):
self.params = params
self.genomeLength = sum( [ param.size for param in self.params ] )
self.eval = eval
self.popSize = popSize
self.numGens = numGens
self.maxTime = maxTime
assert self.numGens or self.maxTime
self.crossProb = crossProb
self.mutateProb = mutateProb
self.selectionMethod = selectionMethod or GA.TOURNAMENT
self.verbose = verbose
def decode( self, ind ):
pos = 0
vals = {}
for param in self.params:
vals[ param.name ] = param.decode( ind[ pos: pos + param.size ] )
pos += param.size
return vals
def generate( self ):
return [ random.randint( 0, 1 ) for i in range( self.genomeLength ) ]
def combine( self, pop, fitness ):
newPop = []
for i in range( 0, len( pop ), 2 ):
i1 = self.select( pop, fitness )
i2 = self.select( pop, fitness )
i1, i2 = self.cross( copy( i1 ), copy( i2 ) )
self.mutate( i1 )
self.mutate( i2 )
newPop += [ i1, i2 ]
return newPop
def cross( self, i1, i2 ):
if random.random() < self.crossProb:
pos = random.randint( 0, min( len( i1 ), len( i2 ) ) - 1 )
return i1[:pos] + i2[pos:], i2[:pos] + i1[pos:]
else:
return i1, i2
def mutate( self, ind ):
for i in range( len( ind ) ):
if random.random() < self.mutateProb:
ind[i] = int( not ind[i] )
def select( self, pop, fitness ):
if self.selectionMethod == GA.ROULETTE:
minFitness = min( fitness )
if minFitness < 0:
fitness = [ score - minFitness for score in fitness ]
total = sum( fitness )
target = random.uniform( 0, total )
inc = 0
for ind, score in zip( pop, fitness ):
inc += score
if inc >= target:
return ind
raise RuntimeError
elif self.selectionMethod == GA.TOURNAMENT:
i1 = random.randint( 0, len( pop ) - 1 )
i2 = random.randint( 0, len( pop ) - 1 )
if fitness[i1] > fitness[i2]:
return pop[i1]
else:
return pop[i2]
else:
raise NotImplemented( self.selectionMethod )
def run( self ):
pop = [ self.generate() for i in range( self.popSize ) ]
best = None
gen = 0
start = time.time()
while ( self.numGens and gen < self.numGens ) or ( self.maxTime and time.time() - start < self.maxTime ):
gen += 1
decodedInds = map( self.decode, pop )
fitness = map( self.eval, decodedInds )
for score, bits, ind in zip( fitness, pop, decodedInds ):
if not best or score > bestScore:
bestScore = score
best = copy( ind )
bestGen = gen
bestBits = bits
if self.verbose:
print '%d %.2f %.2f %.2f %.2f %.2f %d' % ( gen, time.time() - start, min( fitness ), sum( fitness ) / float( len( fitness ) ), max( fitness ), bestScore, bestGen )
pop = self.combine( pop, fitness )
return best
@staticmethod
def test():
def eval( vals ):
til = vals[ 'testIntList' ]
return vals[ 'testBool' ] + \
vals[ 'testInt' ] / vals[ 'testFloat' ] + \
int( vals[ 'testEnum' ] == 5 ) + \
-sum( [ abs( i - val ) for i, val in enumerate( vals[ 'testFloatList' ] ) ] ) + \
int( til[0] * til[1] == til[2] * vals[ 'testInt' ] )
sol = GA( [ GA.Param.bool( 'testBool' ),
GA.Param.int( 'testInt', 0, 10 ),
GA.Param.float( 'testFloat', -20, 20, 0.1 ),
GA.Param.enum( 'testEnum', range( 10 ) ),
GA.Param.floatList( 'testFloatList', 0, 3, 0.1, 3 ),
GA.Param.intList( 'testIntList', 1, 10, 3 ),
], eval, maxTime = 5, verbose = True ).run()
assert sol[ 'testBool' ]
assert sol[ 'testInt' ] == 10
assert sol[ 'testFloat' ] <= 0.1
assert sol[ 'testEnum' ] == 5
assert all( [ abs( val - i ) <= 0.1 for i, val in enumerate( sol[ 'testFloatList' ] ) ] )
til = sol[ 'testIntList' ]
assert til[0] * til[1] == til[2] * sol[ 'testInt' ]
if __name__ == '__main__':
GA.test()
| Python |
import re
import copy
import operator
class LexerToken:
def __init__( self, type, value ):
self.type = type
self.value = value
def __eq__( self, token ):
return self.type == token.type and self.value == token.value
def __repr__( self ):
return 'LexerToken( %s, \'%s\' )' % ( self.type, self.value )
class LexerRule:
def __init__( self, name, pattern, ignore = False ):
self.name = name
self.pattern = pattern
self.ignore = ignore
self.rule = re.compile( self.pattern )
def __repr__( self ):
return 'LexerRule( %s, \'%s\' )' % ( self.name, self.pattern )
def __eq__( self, rule ):
return self.name == rule.name and self.pattern == rule.pattern and self.ignore == rule.ignore
def apply( self, s ):
m = self.rule.match( s )
if m and m.start() == 0:
return LexerToken( self.name, s[:m.end()] )
class Lexer:
def __init__( self, rules ):
self.rules = rules
self.ruleMap = dict( [ ( rule.name, rule ) for rule in self.rules ] )
def __repr__( self ):
return 'Lexer( %s )' % self.rules
def lex( self, s ):
tokens = []
pos = 0
while pos < len( s ):
results = filter( lambda result: result[1], [ ( rule, rule.apply( s[pos:] ) ) for rule in self.rules ] )
assert len( results ) == 1, 'parse error: %s, %s' % ( tokens, s[pos:] )
if not results[0][0].ignore:
tokens.append( results[0][1] )
pos += len( results[0][1].value )
return tokens
@staticmethod
def test():
lexer = Lexer( [ LexerRule( 'ws', '\s+' ),
LexerRule( 'num', '\d+\.?\d*' ),
LexerRule( 'id', '[a-zA-Z][\w_-]*' ),
LexerRule( 'str', '\".*\"' ),
] )
assert lexer.lex( '12 \n3.14 foo21_-bar "hello world"' ) == [
LexerToken( 'num', '12' ),
LexerToken( 'ws', ' \n' ),
LexerToken( 'num', '3.14' ),
LexerToken( 'ws', ' ' ),
LexerToken( 'id', 'foo21_-bar' ),
LexerToken( 'ws', ' ' ),
LexerToken( 'str', '"hello world"' ),
]
class ParserResult:
def __init__( self, type, value, children ):
self.type = type
self.value = value
self.children = children
def __repr__( self, tabs = '' ):
return '%s%s %s\n%s' % ( tabs, self.type, self.value, ''.join( [ child.__repr__( tabs + ' ' ) for child in self.children ] ) )
def __eq__( self, result ):
return self.type == result.type and self.value == result.value and self.children == result.children
class ParserRule:
AND = 'AND'
OR = 'OR'
LITERAL = 'LITERAL'
ONEORMORE = 'ONEORMORE'
ZEROORMORE = 'ZEROORMORE'
def __init__( self, type, name, children ):
self.type = type
self.name = name
self.children = children
def __repr__( self, tabs = '' ):
return '%s%s %s\n%s' % ( tabs, self.type, self.name, ''.join( [ child.__repr__( tabs + ' ' ) for child in self.children ] ) )
def apply( self, tokens ):
if self.type == ParserRule.LITERAL:
if tokens and tokens[0].type == self.name:
return ParserResult( self.name, tokens[0].value, [] ), tokens[1:]
elif self.type == ParserRule.AND:
if len( tokens ) >= len( self.children ):
childTokens = copy.copy( tokens )
childResults = []
for child in self.children:
childResult = child.apply( childTokens )
if not childResult:
return
childResults.append( childResult[0] )
childTokens = childResult[1]
return ParserResult( self.name, None, childResults ), childTokens
elif self.type == ParserRule.OR:
for child in self.children:
childResult = child.apply( copy.copy( tokens ) )
if childResult:
return ParserResult( self.name, None, [ childResult[0] ] ), childResult[1]
elif self.type == ParserRule.ONEORMORE:
assert len( self.children ) == 1
childResult = self.children[0].apply( tokens )
if childResult:
childResults = [ childResult[0] ]
childTokens = childResult[1]
while True:
childResult = self.children[0].apply( copy.copy( childTokens ) )
if childResult:
childResults.append( childResult[0] )
childTokens = childResult[1]
else:
return ParserResult( self.name, None, childResults ), childTokens
elif self.type == ParserRule.ZEROORMORE:
assert len( self.children ) == 1
childResults = []
childTokens = tokens
while True:
childResult = self.children[0].apply( copy.copy( childTokens ) )
if childResult:
childResults.append( childResult[0] )
childTokens = childResult[1]
else:
return ParserResult( self.name, None, childResults ), childTokens
else:
raise RuntimeError( 'invalid parser rule type %s' % self.type )
class Parser:
def __init__( self, lexer, rules ):
self.lexer = lexer
self.root = rules[0]
rules += [ ParserRule( ParserRule.LITERAL, rule.name, [] ) for rule in self.lexer.rules ]
ruleMap = dict( [ ( rule.name, rule ) for rule in rules ] )
for rule in ruleMap.values():
for i in range( len( rule.children ) ):
child = rule.children[i]
if isinstance( child, str ):
if child in ruleMap:
child = rule.children[i] = ruleMap[ child ]
else:
raise RuntimeError( 'unknown rule %s' % rule.children[i] )
child.parent = rule
def __repr__( self ):
return 'Parser( %s, %s )' % ( self.lexer, self.root )
def parse( self, s ):
result = self.root.apply( self.lexer.lex( s ) )
if not result:
raise RuntimeError( 'failed to parse' )
elif result[1]:
raise RuntimeError( 'leftover tokens: result = %s, tokens = %s' % result )
else:
return result[0]
@staticmethod
def load( s ):
parser = Parser(
Lexer( [
LexerRule( 'ws', '\s+', True ),
LexerRule( 'id', '[a-zA-Z][\w_-]*' ),
LexerRule( 'str', '\'.*\'' ),
LexerRule( 'semicolon', ';' ),
LexerRule( 'equals', '=' ),
LexerRule( 'star', '\*' ),
LexerRule( 'plus', '\+' ),
LexerRule( 'bar', '\|' ),
LexerRule( 'tilde', '\~' ),
] ),
[
ParserRule( ParserRule.ONEORMORE, 'grammar', [ 'line' ] ),
ParserRule( ParserRule.AND, 'line', [ 'id', 'equals', 'rule', 'semicolon' ] ),
ParserRule( ParserRule.OR, 'rule', [ 'orRule', 'oneOrMoreRule', 'zeroOrMoreRule', 'lexerRule', 'negativeLexerRule', 'andRule' ] ),
ParserRule( ParserRule.AND, 'orRule', [ 'id', 'orRuleContent' ] ),
ParserRule( ParserRule.ONEORMORE, 'orRuleContent', [ 'orRuleContentIter' ] ),
ParserRule( ParserRule.AND, 'orRuleContentIter', [ 'bar', 'id' ] ),
ParserRule( ParserRule.AND, 'oneOrMoreRule', [ 'id', 'plus' ] ),
ParserRule( ParserRule.AND, 'zeroOrMoreRule', [ 'id', 'star' ] ),
ParserRule( ParserRule.AND, 'lexerRule', [ 'str' ] ),
ParserRule( ParserRule.AND, 'negativeLexerRule', [ 'tilde', 'str' ] ),
ParserRule( ParserRule.ONEORMORE, 'andRule', [ 'id' ] ),
] )
grammar = parser.parse( s )
lexerRules = []
rules = []
for line in grammar.children:
id = line.children[0].value
rule = line.children[2].children[0]
if rule.type == 'lexerRule':
lexerRules.append( LexerRule( id, rule.children[0].value[1:-1] ) )
elif rule.type == 'negativeLexerRule':
lexerRules.append( LexerRule( id, rule.children[1].value[1:-1], True ) )
elif rule.type == 'orRule':
ids = [ rule.children[0].value ] + [ iter.children[1].value for iter in rule.children[1].children ]
rules.append( ParserRule( ParserRule.OR, id, ids ) )
elif rule.type == 'andRule':
ids = [ child.value for child in rule.children ]
rules.append( ParserRule( ParserRule.AND, id, ids ) )
elif rule.type == 'oneOrMoreRule':
rules.append( ParserRule( ParserRule.ONEORMORE, id, [ rule.children[0].value ] ) )
elif rule.type == 'zeroOrMoreRule':
rules.append( ParserRule( ParserRule.ZEROORMORE, id, [ rule.children[0].value ] ) )
else:
raise RuntimeError( 'unknown rule type %s' % rule.type )
return Parser( Lexer( lexerRules ), rules )
@staticmethod
def test():
parser = Parser.load( '''
ws = ~'\s+';
num = '\d+\.?\d*';
id = '[a-zA-Z][\w_-]*';
str = '\".*\"';
lparen = '\(';
rparen = '\)';
expr = parenExpr | id | num | str;
parenExpr = lparen exprContent rparen;
exprContent = expr+;
''' )
assert ParserResult( 'expr', None, [
ParserResult( 'parenExpr', None, [
ParserResult( 'lparen', '(', [] ),
ParserResult( 'exprContent', None, [
ParserResult( 'expr', None, [
ParserResult( 'id', 'foo', [] ),
] ),
ParserResult( 'expr', None, [
ParserResult( 'num', '3.14', [] ),
] ),
ParserResult( 'expr', None, [
ParserResult( 'str', '"hello"', [] ),
] ),
] ),
ParserResult( 'rparen', ')', [] ),
] ),
] ) == parser.parse( '( foo 3.14 "hello" )' )
class LispExpr:
VAR = 'VAR'
NUM = 'NUM'
STR = 'STR'
LIST = 'LIST'
def __init__( self, type, value ):
self.type = type
self.value = value
def __repr__( self ):
return 'LispExpr( %s, %s)' % ( self.type, self.value )
class LispValue:
NUM = 'NUM'
STR = 'STR'
FUNC = 'FUNC'
def __init__( self, type, value ):
self.type = type
self.value = value
def __repr__( self ):
return 'LispValue( %s, %s )' % ( self.type, self.value )
def __eq__( self, value ):
return self.type == value.type and self.value == value.value
class LispInterpreter:
def __init__( self ):
self.parser = Parser.load( '''
ws = ~'\s+';
num = '\d+\.?\d*';
id = '[a-zA-Z][\w_-]*';
str = '\".*\"';
lparen = '\(';
rparen = '\)';
program = expr*;
expr = parenExpr | id | num | str;
parenExpr = lparen exprContent rparen;
exprContent = expr+;
''' )
def run( self, s ):
program = self.parser.parse( s )
env = {}
vals = [ self.eval( self.convertExpr( expr ), env ) for expr in program.children ]
return vals[-1]
def convertExpr( self, expr ):
value = expr.children[0]
if value.type == 'id':
return LispExpr( LispExpr.VAR, value.value )
elif value.type == 'num':
if '.' in value.value:
return LispExpr( LispExpr.NUM, LispValue( LispValue.NUM, float( value.value ) ) )
else:
return LispExpr( LispExpr.NUM, LispValue( LispValue.NUM, int( value.value ) ) )
elif value.type == 'str':
return LispExpr( LispExpr.STR, LispValue( LispValue.STR, value.value[1:-1] ) )
elif value.type == 'parenExpr':
return LispExpr( LispExpr.LIST, [ self.convertExpr( child ) for child in value.children[1].children ] )
else:
raise RuntimeError
def eval( self, expr, env ):
if expr.type == LispExpr.VAR:
assert expr.value in env, 'unknown var %s' % expr.value
return env[expr.value]
elif expr.type in ( LispExpr.NUM, LispExpr.STR ):
return expr.value
elif expr.type == LispExpr.LIST:
return self.apply( expr.value[0], expr.value[1:], env )
else:
raise RuntimeError
def apply( self, functorExpr, argExprs, env ):
if functorExpr.type == LispExpr.VAR:
builtinName = 'builtin_%s' % functorExpr.value
if hasattr( self, builtinName ):
return getattr( self, builtinName )( argExprs, env )
functor = self.eval( functorExpr, env )
assert functor.type == LispValue.FUNC
argNames, body = functor.value
argValues = [ self.eval( argExpr, env ) for argExpr in argExprs ]
assert len( argNames ) == len( argValues )
funcEnv = copy.copy( env )
for argName, argValue in zip( argNames, argValues ):
funcEnv[ argName ] = argValue
return self.eval( body, funcEnv )
def builtin_def( self, args, env ):
assert len( args ) == 2
header = args[0]
assert header.type == LispExpr.LIST
nameExpr = header.value[0]
assert nameExpr.type == LispExpr.VAR
name = nameExpr.value
argExprs = header.value[1:]
assert all( [ argExpr.type == LispExpr.VAR for argExpr in argExprs ] )
argNames = [ argExpr.value for argExpr in argExprs ]
body = args[1]
env[name] = LispValue( LispValue.FUNC, ( argNames, body ) )
def builtin_add( self, args, env ):
vals = [ self.eval( arg, env ) for arg in args ]
assert all( [ val.type == vals[0].type for val in vals ] )
result = vals[0].value
for val in vals[1:]:
result += val.value
return LispValue( vals[0].type, result )
def builtin_sub( self, args, env ):
vals = [ self.eval( arg, env ) for arg in args ]
assert all( [ val.type == vals[0].type for val in vals ] )
result = vals[0].value
for val in vals[1:]:
result -= val.value
return LispValue( vals[0].type, result )
def builtin_mul( self, args, env ):
vals = [ self.eval( arg, env ) for arg in args ]
assert all( [ val.type == vals[0].type for val in vals ] )
result = vals[0].value
for val in vals[1:]:
result *= val.value
return LispValue( vals[0].type, result )
def builtin_div( self, args, env ):
vals = [ self.eval( arg, env ) for arg in args ]
assert all( [ val.type == vals[0].type for val in vals ] )
result = vals[0].value
for val in vals[1:]:
result /= val.value
return LispValue( vals[0].type, result )
@staticmethod
def test():
assert LispValue( LispValue.NUM, 4 ) == LispInterpreter().run( '( def ( sqrt x ) ( mul x x ) ) ( sqrt 2 )' )
if __name__ == '__main__':
Lexer.test()
Parser.test()
LispInterpreter.test()
| Python |
import math
def memoize( f ):
d = {}
def closure( *args ):
if args not in d:
d[args] = f( *args )
return d[args]
return closure
def prob1():
return sum( filter( lambda i: not i % 3 or not i % 5, range( 1, 1000 ) ) )
fibs = [ 1, 1 ]
def fibsTo( n ):
while fibs[-1] < n:
fibs.append( fibs[-1] + fibs[-2] )
return fibs[:-1]
def isEven( n ):
return n % 2 == 0
def prob2():
return sum( filter( isEven, fibsTo( 4000000 ) ) )
@memoize
def isPrime( n ):
n = abs( n )
if n < 1:
return False
elif n == 1:
return True
else:
i = 2
while i * i <= n:
if not n % i:
return False
i += 1
return True
def primeFactors( n ):
factors = []
while not isPrime( n ):
i = 2
while i < n:
if not n % i and isPrime( i ):
factors.append( i )
n /= i
break
i += 1
factors.append( n )
return factors
def prob3():
return max( primeFactors( 600851475143 ) )
def isPalindrome( s ):
for i in range( len( s ) / 2 ):
if s[i] != s[len(s)-1-i]:
return False
return True
def getProducts( min, max ):
products = []
for i in range( min, max ):
for j in range( i, max ):
products.append( i * j )
return products
def prob4():
return max( map( int, filter( isPalindrome, map( str, getProducts( 100, 1000 ) ) ) ) )
def divisibleByRange( min, max, n ):
for i in range( min, max ):
if n % i:
return False
return True
def prob5():
i = 1
while True:
if divisibleByRange( 1, 21, i ):
return i
i += 1
def prob6():
n = 100
s = sum( range( n + 1 ) )
return s * s - sum( [ i * i for i in range( n + 1 ) ] )
def getPrimes( n ):
primes = [2]
while len( primes ) < n:
p = primes[-1] + 1
while not isPrime( p ):
p += 1
primes.append( p )
return primes
def prob7():
return getPrimes( 10001 )[-1]
def product( l ):
n = 1
for i in l:
n *= i
return n
def prob8():
s = '7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450'
l = 5
return max( [ product( map( int, s[i:i+l] ) ) for i in range( len( s ) - l ) ] )
def isPythTriplet( a, b, c ):
return a < b and b < c and a * a + b * b == c * c
def adders( n ):
return [ ( i, n - i ) for i in range( n + 1 ) ]
def prob9():
n = 1000
for a, bc in adders( n ):
for b, c in adders( bc ):
if isPythTriplet( a, b, c ):
return a * b * c
def prob10():
n = 2
s = 0
while n < 2000000:
if isPrime( n ):
s += n
n += 1
return s
def prob11():
s = '''08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48'''
l = 4
grid = [ map( int, line.split() ) for line in s.split( '\n' ) ]
w = len( grid[0] )
h = len( grid )
max = -1
for i in range( w ):
for j in range( h ):
for di in ( -1, 0, 1 ):
for dj in ( -1, 0, 1 ):
maxi = i + l * di - 1
maxj = j + l * dj - 1
if ( di or dj ) and ( maxi >= 0 and maxi < w and maxj >= 0 and maxj < h ):
s = product( [ grid[ i + di * k ][ j + dj * k ] for k in range( l ) ] )
if s > max:
max = s
return max
def getNumFactors( n ):
nf = 2
i = 2
while i <= n / 2:
if n % i == 0:
nf += 1
i += 1
return nf
return filter( lambda i: n % i == 0, range( 1, n + 1 ) )
#slow
def prob12():
i = 1
n = 1
f = 0
while f <= 500:
i += 1
n += i
f = getNumFactors( n )
return n
def prob13():
s = '''37107287533902102798797998220837590246510135740250
46376937677490009712648124896970078050417018260538
74324986199524741059474233309513058123726617309629
91942213363574161572522430563301811072406154908250
23067588207539346171171980310421047513778063246676
89261670696623633820136378418383684178734361726757
28112879812849979408065481931592621691275889832738
44274228917432520321923589422876796487670272189318
47451445736001306439091167216856844588711603153276
70386486105843025439939619828917593665686757934951
62176457141856560629502157223196586755079324193331
64906352462741904929101432445813822663347944758178
92575867718337217661963751590579239728245598838407
58203565325359399008402633568948830189458628227828
80181199384826282014278194139940567587151170094390
35398664372827112653829987240784473053190104293586
86515506006295864861532075273371959191420517255829
71693888707715466499115593487603532921714970056938
54370070576826684624621495650076471787294438377604
53282654108756828443191190634694037855217779295145
36123272525000296071075082563815656710885258350721
45876576172410976447339110607218265236877223636045
17423706905851860660448207621209813287860733969412
81142660418086830619328460811191061556940512689692
51934325451728388641918047049293215058642563049483
62467221648435076201727918039944693004732956340691
15732444386908125794514089057706229429197107928209
55037687525678773091862540744969844508330393682126
18336384825330154686196124348767681297534375946515
80386287592878490201521685554828717201219257766954
78182833757993103614740356856449095527097864797581
16726320100436897842553539920931837441497806860984
48403098129077791799088218795327364475675590848030
87086987551392711854517078544161852424320693150332
59959406895756536782107074926966537676326235447210
69793950679652694742597709739166693763042633987085
41052684708299085211399427365734116182760315001271
65378607361501080857009149939512557028198746004375
35829035317434717326932123578154982629742552737307
94953759765105305946966067683156574377167401875275
88902802571733229619176668713819931811048770190271
25267680276078003013678680992525463401061632866526
36270218540497705585629946580636237993140746255962
24074486908231174977792365466257246923322810917141
91430288197103288597806669760892938638285025333403
34413065578016127815921815005561868836468420090470
23053081172816430487623791969842487255036638784583
11487696932154902810424020138335124462181441773470
63783299490636259666498587618221225225512486764533
67720186971698544312419572409913959008952310058822
95548255300263520781532296796249481641953868218774
76085327132285723110424803456124867697064507995236
37774242535411291684276865538926205024910326572967
23701913275725675285653248258265463092207058596522
29798860272258331913126375147341994889534765745501
18495701454879288984856827726077713721403798879715
38298203783031473527721580348144513491373226651381
34829543829199918180278916522431027392251122869539
40957953066405232632538044100059654939159879593635
29746152185502371307642255121183693803580388584903
41698116222072977186158236678424689157993532961922
62467957194401269043877107275048102390895523597457
23189706772547915061505504953922979530901129967519
86188088225875314529584099251203829009407770775672
11306739708304724483816533873502340845647058077308
82959174767140363198008187129011875491310547126581
97623331044818386269515456334926366572897563400500
42846280183517070527831839425882145521227251250327
55121603546981200581762165212827652751691296897789
32238195734329339946437501907836945765883352399886
75506164965184775180738168837861091527357929701337
62177842752192623401942399639168044983993173312731
32924185707147349566916674687634660915035914677504
99518671430235219628894890102423325116913619626622
73267460800591547471830798392868535206946944540724
76841822524674417161514036427982273348055556214818
97142617910342598647204516893989422179826088076852
87783646182799346313767754307809363333018982642090
10848802521674670883215120185883543223812876952786
71329612474782464538636993009049310363619763878039
62184073572399794223406235393808339651327408011116
66627891981488087797941876876144230030984490851411
60661826293682836764744779239180335110989069790714
85786944089552990653640447425576083659976645795096
66024396409905389607120198219976047599490197230297
64913982680032973156037120041377903785566085089252
16730939319872750275468906903707539413042652315011
94809377245048795150954100921645863754710598436791
78639167021187492431995700641917969777599028300699
15368713711936614952811305876380278410754449733078
40789923115535562561142322423255033685442488917353
44889911501440648020369068063960672322193204149535
41503128880339536053299340368006977710650566631954
81234880673210146739058568557934581403627822703280
82616570773948327592232845941706525094512325230608
22918802058777319719839450180888072429661980811197
77158542502016545090413245809786882778948721859617
72107838435069186155435662884062257473692284509516
20849603980134001723930671666823555245252804609722
53503534226472524250874054075591789781264330331690'''
return str( sum( map( int, s.split() ) ) )[:10]
collatzLens = { 1: 1 }
def getCollatzLen( n ):
if n in collatzLens:
return collatzLens[n]
else:
if n % 2:
c = 3 * n + 1
else:
c = n / 2
l = 1 + getCollatzLen( c )
collatzLens[n] = l
return l
def prob14():
assert 10 == getCollatzLen( 13 )
return max( range( 1, 1000000 ), key = getCollatzLen )
@memoize
def getLatticePaths( n, m ):
if n == 0 and m == 0:
return 1
else:
p = 0
if n > 0:
p += getLatticePaths( n - 1, m )
if m > 0:
p += getLatticePaths( n, m - 1 )
return p
def prob15():
assert 6 == getLatticePaths( 2, 2 )
return getLatticePaths( 20, 20 )
def prob16():
return sum( map( int, str( 2 ** 1000 ) ) )
def numToWord( n ):
assert n <= 1000, str( n )
if n == 1000:
return 'onethousand'
elif n >= 100:
if n % 100:
return numToWord( n / 100 ) + 'hundredand' + numToWord( n % 100 )
else:
return numToWord( n / 100 ) + 'hundred'
elif n > 10 and n < 20:
return ( 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' )[ n - 11 ]
elif n >= 10:
return ( '', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' )[ n / 10 ] + numToWord( n % 10 )
else:
return ( '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' )[ n ]
def prob17():
assert len( numToWord( 342 ) ) == 23
assert len( numToWord( 115 ) ) == 20
assert sum( map( len, map( numToWord, range( 1, 6 ) ) ) ) == 19
return sum( map( len, map( numToWord, range( 1, 1001 ) ) ) )
def subTris( tri ):
return [ row[:-1] for row in tri[1:] ], [ row[1:] for row in tri[1:] ]
def triMaxSum( tri ):
head = tri[0][0]
if len( tri ) == 1:
return head
else:
return max( [ head + triMaxSum( sub ) for sub in subTris( tri ) ] )
def prob18():
s = '''75
95 64
17 47 82
18 35 87 10
20 04 82 47 65
19 01 23 75 03 34
88 02 77 73 07 63 67
99 65 04 28 06 16 70 92
41 41 26 56 83 40 80 70 33
41 48 72 33 47 32 37 16 94 29
53 71 44 65 25 43 91 52 97 51 14
70 11 33 28 77 73 17 78 39 68 17 57
91 71 52 38 17 14 91 43 58 50 27 29 48
63 66 04 68 89 53 67 30 73 16 69 87 40 31
04 62 98 27 23 09 70 98 73 93 38 53 60 04 23'''
tri = [ map( int, line.split() ) for line in s.split( '\n' ) ]
return triMaxSum( tri )
def prob19():
year = 1901
month = 1
date = 1
day = 2
numFirstSundays = 0
while year < 2001:
if date == 1 and day == 7:
numFirstSundays += 1
day += 1
if day > 7:
day = 1
date += 1
if date > 30 and month in ( 4, 6, 9, 11 ):
month += 1
date = 1
elif date > 31 and month in ( 1, 3, 5, 7, 8, 10, 12 ):
month += 1
date = 1
elif date > 28 and month == 2 and ( year % 4 or ( not year % 100 and year % 400 ) ):
month += 1
date = 1
elif date > 29 and month == 2:
month += 1
date = 1
if month > 12:
year += 1
month = 1
assert year == 2001 and month == 1 and date == 1 and day == 1 #jan 1 2001 was a monday
return numFirstSundays
@memoize
def fac( n ):
return product( range( 1, n + 1 ) )
def facSum( n ):
return sum( map( int, str( fac( n ) ) ) )
def prob20():
assert facSum( 10 ) == 27
return facSum( 100 )
def getFactorSum( n ):
sum = 1
for i in range( 2, n / 2 + 1 ):
if not n % i:
sum += i
return sum
def prob21():
fss = dict( [ ( i, getFactorSum( i ) ) for i in range( 1, 10001 ) ] )
assert fss[fss[220]] == 220
assert fss[fss[284]] == 284
sum = 0
for i, fs in fss.iteritems():
if fs != i and fs in fss and fss[fs] == i:
sum += i
return sum
def getNameScore( name ):
return sum( [ ord(c) - ord('a') + 1 for c in name ] )
def prob22():
names = sorted( [ name.strip( '"' ).lower() for name in open( 'names.txt' ).read().split(',') ] )
return sum( [ ( i + 1 ) * getNameScore( name ) for i, name in enumerate( names ) ] )
def isAbundant( n ):
return getFactorSum( n ) > n
def addsTo( n, adders ):
nadders = filter( lambda a: a < n, adders )
for a in nadders:
if n - a in nadders:
return True
return False
def getSums( l ):
sums = set()
for i in range( len( l ) ):
for j in range( i, len( l ) ):
sums.add( l[i] + l[j] )
return sums
def prob23():
abundantNums = filter( isAbundant, range( 1, 28124 ) )
sums = getSums( abundantNums )
return sum( filter( lambda i: i not in sums, range( 1, 28124 ) ) )
def permute( l ):
if not l:
return [[]]
else:
r = []
for i in range( len( l ) ):
for pi in permute( l[:i] + l[i+1:] ):
r.append( [l[i]] + pi )
return r
def prob24():
assert [2,1,0] == sorted( permute( range( 3 ) ) )[5]
perms = sorted( list( set( [ ''.join( map( str, perm ) ) for perm in permute( range( 10 ) ) ] ) ) )
assert len( perms ) == fac( 10 )
assert all( [ perms[i] < perms[i+1] for i in range( len( perms) - 1 ) ] )
return perms[999999] #lame
def prob25():
a = 1
b = 1
i = 2
while len( str( b ) ) < 1000:
c = a + b
a = b
b = c
i += 1
return i
def decimalExpansion( num, denom, n ):
s = ''
for i in range( n ):
s += str( int( num / denom ) )
num = ( num % denom ) * 10
return s
def isCycle( s, n ):
return all( [ s[i*n:(i+1)*n] == s[:n] for i in range( len( s ) / n ) ] )
def cycleLength( s ):
cls = filter( lambda i: isCycle( s, i ), range( 1, len( s ) / 2 + 1 ) )
if cls:
return min( cls )
else:
return 0
def recipCycleLength( denom ):
s = decimalExpansion( 1., denom, 2000 )
cls = [ cycleLength( s[i:] ) for i in range( 10 ) ]
if cls:
return max( cls )
else:
return 0
def prob26():
assert recipCycleLength( 7 ) == 6
return max( range( 1, 1000 ), key = recipCycleLength )
def numQuadPrimes( a, b ):
i = 0
while isPrime( i * i + a * i + b ):
i += 1
return i
def prob27():
assert numQuadPrimes( 1, 41 ) == 40
assert numQuadPrimes( -79, 1601 ) == 80
max = -1
prod = -1
for a in range( -999, 1000 ):
for b in range( -999, 1000 ):
n = numQuadPrimes( a, b )
if n > max:
max = n
prod = a * b
return prod
class Board:
def __init__( self, n ):
assert n % 2
self.n = n
self.board = [ 0 ] * self.n * self.n
def __getitem__( self, ( i, j ) ):
assert i < self.n and j < self.n
return self.board[ j * self.n + i ]
def __setitem__( self, ( i, j ), v ):
assert i < self.n and j < self.n
self.board[ j * self.n + i ] = v
def __repr__( self ):
return '\n'.join( map( str, [ self.board[ j * self.n : ( j + 1 ) * self.n ] for j in range( self.n ) ] ) )
def fillSpiral( self ):
mid = self.n / 2
self[mid,mid] = 1
v = 2
for layer in range( 1, self.n / 2 + 1 ):
for j in range( mid - layer + 1, mid + layer + 1 ):
self[mid + layer, j] = v
v += 1
for i in range( mid + layer - 1, mid - layer - 1, -1 ):
self[i, mid + layer] = v
v += 1
for j in range( mid + layer - 1, mid - layer - 1, -1 ):
self[mid - layer, j ] = v
v += 1
for i in range( mid - layer + 1, mid + layer + 1 ):
self[i, mid - layer] = v
v += 1
assert v == self.n * self.n + 1
def fillReverseSpiral( self ):
mid = self.n / 2
self[mid,mid] = 1
v = 2
for layer in range( 1, self.n / 2 + 1 ):
for j in range( mid + layer - 1, mid - layer - 1, -1 ):
self[mid + layer, j] = v
v += 1
for i in range( mid + layer - 1, mid - layer - 1, -1 ):
self[i, mid - layer] = v
v += 1
for j in range( mid - layer + 1, mid + layer + 1 ):
self[mid - layer, j ] = v
v += 1
for i in range( mid - layer + 1, mid + layer + 1 ):
self[i, mid + layer] = v
v += 1
assert v == self.n * self.n + 1
def diags( self ):
mid = self.n / 2
return sum( [ [ self[i,i], self[self.n-i-1,i], self[i,self.n-i-1], self[self.n-i-1,self.n-i-1] ] for i in range(mid) ], [ self[mid,mid] ] )
def diagSum( self ):
return sum( self.diags() )
def prob28():
b = Board( 5 )
b.fillSpiral()
assert 101 == b.diagSum()
b = Board( 1001 )
b.fillSpiral()
return b.diagSum()
def prob29():
s = set()
for a in range( 2, 101 ):
for b in range( 2, 101 ):
s.add( a ** b )
return len( s )
def prob30():
s = 0
for i in range( 2, 1000000 ):
if i == sum( [ d ** 5 for d in map( int, str( i ) ) ] ):
s += i
return s
@memoize
def coinPerms( n ):
if n == 0:
return [()]
else:
r = set()
for i in ( 1, 2, 5, 10, 20, 50, 100, 200 ):
if n >= i:
for ri in coinPerms( n - i ):
r.add( tuple( sorted( (i,) + ri ) ) )
return r
def prob31():
perms = list( coinPerms( 200 ) )
assert all( [ sum( perm ) == 200 for perm in perms ] )
return len( perms )
def splits( s ):
return [ ( s[:l], s[l:] ) for l in range( 1, len( s ) ) ]
def prob32():
prods = set()
for perm in permute( range( 1, 10 ) ):
permStr = ''.join( map( str, perm ) )
for astr, bc in splits( permStr ):
for bstr, cstr in splits( bc ):
a, b, c = map( int, ( astr, bstr, cstr ) )
if a * b == c:
prods.add( c )
return sum( prods )
def fracPerms( num, den ):
n0 = int( str( num )[0] )
n1 = int( str( num )[1] )
d0 = int( str( den )[0] )
d1 = int( str( den )[1] )
if 0 != d0 and n1 != d1:
l = []
if n0 == d1:
l.append( ( n1, d0 ) )
if n1 == d0:
l.append( ( n0, d1 ) )
return l
else:
return []
def prob33():
ns = []
ds = []
for den in range( 10, 100 ):
for num in range( 10, den ):
for n, d in fracPerms( num, den ):
if d and float( num ) / float( den ) == float( n ) / float( d ):
ns.append( n )
ds.append( d )
return product( ds ) / product( ns )
def prob34():
s = 0
for i in range( 3, 1000000 ):
if i == sum( map( fac, map( int, str( i ) ) ) ):
s += i
return s
def isCircularPrime( n ):
s = str( n )
for i in range( len( s ) ):
if not isPrime( int( s[i:] + s[:i] ) ):
return False
return True
def prob35():
assert isCircularPrime( 197 )
return sum( map( isCircularPrime, range( 2, 1000000 ) ) )
def isMultibasePalindrome( n ):
return isPalindrome( str( n ) ) and isPalindrome( str( bin( n ) ).split( 'b' )[-1] )
def prob36():
assert isMultibasePalindrome( 585 )
return sum( filter( isMultibasePalindrome, range( 1000000 ) ) )
def isTruncatablePrime( n ):
s = str( n )
for i in range( len( s ) ):
if not isPrime( int( s[i:] ) ) or ( i and not isPrime( int( s[:-i] ) ) ):
return False
return True
def prob37():
assert isTruncatablePrime( 3797 )
i = 8
l = []
while len( l ) < 11:
if isTruncatablePrime( i ):
l.append( i )
i += 1
return sum( l )
def concatProduct( n, l ):
return ''.join( map( str, [ n * i for i in l ] ) )
def isPanDigital( s ):
return ''.join( sorted( s ) ) == ''.join( map( str, range( 1, len( s ) + 1 ) ) )
def prob38():
assert isPanDigital( concatProduct( 9, range( 1, 6 ) ) )
assert isPanDigital( concatProduct( 192, range( 1, 4 ) ) )
max = -1
for i in range( 1, 1000000 ):
j = 3
s = concatProduct( i, range( 1, j ) )
while len( s ) < 10:
if len( s ) == 9 and isPanDigital( s ) and int( s ) > max:
max = int( s )
j += 1
s = concatProduct( i, range( 1, j ) )
return max
def numTris( p ):
n = 0
for i in range( 1, p ):
for j in range( i + 1, p ):
k = p - i - j
if i * i + j * j == k * k:
n += 1
return n
def prob39():
assert 3 == numTris( 120 )
return max( range( 1001 ), key = numTris )
def prob40():
s = ''
i = 1
while len( s ) < 1000000:
s += str( i )
i += 1
return product( map( int, [ s[ 10 ** i - 1 ] for i in range( 7 ) ] ) )
def prob41():
for l in range( 10, 0, -1 ):
perms = map( int, [ ''.join( map( str, perm ) ) for perm in permute( range( 1, l ) ) ] )
primes = filter( isPrime, perms )
if primes:
return max( primes )
tris = [1]
def isTri( n ):
if n > tris[-1]:
while tris[-1] < n:
tris.append( tris[-1] + len( tris ) + 1 )
return n in tris
def prob42():
assert isTri( 55 )
assert not isTri( 56 )
words = [ word.strip( '"' ).lower() for word in open( 'words.txt' ).read().split( ',' ) ]
scores = [ sum( [ ord( c ) - ord( 'a' ) + 1 for c in word ] ) for word in words ]
return sum( map( isTri, scores ) )
def prob43():
def cond( n ):
s = str( n )
def div( i, d ):
return int( s[i-1:i+2] ) % d == 0
return div( 2, 2 ) and div( 3, 3 ) and div( 4, 5 ) and div( 5, 7 ) and div( 6, 11 ) and div( 7, 13 ) and div( 8, 17 )
assert cond( 1406357289 )
perms = map( int, [ ''.join( map( str, perm ) ) for perm in permute( range( 10 ) ) ] )
return sum( filter( cond, perms ) )
def prob44():
pents = [ i * ( 3 * i - 1 ) / 2 for i in range( 1, 10000 ) ]
pentSet = set( pents )
l = []
for i in range( len( pents ) ):
for j in range( i ):
d = pents[i] - pents[j]
s = pents[i] + pents[j]
if d in pentSet and s in pentSet:
l.append( d )
return min( l )
pents = [1]
def isPent( n ):
while n > pents[-1]:
i = len( pents ) + 1
pents.append( i * ( 3 * i - 1 ) / 2 )
return n in pents
hexes = [1]
def isHex( n ):
while n > hexes[-1]:
i = len( hexes ) + 1
hexes.append( i * ( 2 * i - 1 ) )
return n in hexes
def prob45():
assert isTri( 40755 ) and isPent( 40755 ) and isHex( 40755 )
i = 1
n = 1
l = []
while len( l ) < 3:
if isPent( n ) and isHex( n ):
l.append( n )
i += 1
n += i
return l[-1]
def isComposite( n ):
return any( [ n % i == 0 for i in range( 2, n ) ] )
def isGoldbach( n ):
for i in filter( isPrime, range( 1, n ) ):
j = 1
c = 2 * j * j + i
while c < n:
j += 1
c = 2 * j * j + i
if c == n:
return True
return False
def prob46():
assert all( map( isGoldbach, ( 9, 15, 21, 25, 27, 33 ) ) )
i = 1
while not ( i % 2 and isComposite( i ) and not isGoldbach( i ) ):
i += 1
return i
@memoize
def getNumPrimeFactors( n ):
c = 0
for i in range( 2, n / 2 + 1 ):
if not n % i and not getNumPrimeFactors( i ):
c += 1
return c
def prob47():
def find( n ):
i = 1
while not all( [ getNumPrimeFactors( i + j ) == n for j in range( n ) ] ):
i += 1
return i
assert find( 2 ) == 14
assert find( 3 ) == 644
return find( 4 )
def prob48():
return str( sum( [ i ** i for i in range( 1, 1001 ) ] ) )[-10:]
def isPermutation( a, b ):
return sorted( a ) == sorted( b )
def arePermutations( l ):
return all( [ isPermutation( l[0], l[i] ) for i in range( 1, len( l ) ) ] )
def isPrime2( n ):
return not getNumPrimeFactors( n )
def prob49():
def cond( a, b ):
n = [ a + b * i for i in range( 3 ) ]
if arePermutations( map( str, n ) ) and all( map( isPrime, n ) ):
return ''.join( map( str, n ) )
assert cond( 1487, 3330 ) == '148748178147'
for a in range( 1000, 10000 ):
for b in range( 1000, ( 10000 - a ) / 2 ):
s = cond( a, b )
if s and ( a, b ) != ( 1487, 3330 ):
return s
def prob50():
def cond( n ):
primes = filter( isPrime, range( 1, n ) )
l = []
for i in range( len( primes ) ):
j = i
s = primes[j]
while s < n and j < len( primes ) - 1:
if isPrime( s ):
l.append( primes[i:j+1] )
j += 1
s += primes[j]
return sum( max( l, key = len ) )
assert cond( 100 ) == 41
assert cond( 1000 ) == 953
return cond( 1000000 )
def prob51():
def replaceDigits( s, perm ):
r = []
for i in range( 10 ):
if i or not perm[0]:
si = ''
for j in range( len( s ) ):
if perm[j]:
si += str( i )
else:
si += s[j]
r.append( si )
return r
@memoize
def replacementPerms( n ):
perms = set()
for l in range( 1, n + 1 ):
for perm in permute( [1] * l + [0] * ( n - l ) ):
perms.add( tuple( perm ) )
return perms
def primeFamily( n ):
s = str( n )
r = []
for perm in replacementPerms( len( s ) ):
r.append( filter( isPrime, map( int, replaceDigits( s, perm ) ) ) )
return max( r, key = len )
assert len( primeFamily( 13 ) ) == 6
assert len( primeFamily( 56003 ) ) == 7
i = 10
while True:
if isPrime( i ):
pf = primeFamily( i )
if len( pf ) == 8:
return min( pf )
i += 1
def prob52():
def cond( n, m ):
return arePermutations( map( str, [ n * i for i in range( 2, m + 1 ) ] ) )
assert cond( 125874, 2 )
i = 1
while not cond( i, 6 ):
i += 1
return i
def prob53():
def c( n, r ):
return fac( n ) / ( fac( r ) * fac( n - r ) )
assert c( 23, 10 ) == 1144066
s = 0
for n in range( 1, 101 ):
for r in range( 1, n ):
if c( n, r ) > 1000000:
s += 1
return s
def prob54():
class Card:
def __init__( self, rank, suit ):
assert rank >= 2 and rank <= 14, 'invalid rank %d' % rank
assert suit in 'hdsc', 'invalid suit %s' % suit
self.rank = rank
self.suit = suit
def __repr__( self ):
return '%s%s' % ( self.rank, self.suit )
def __eq__( self, c ):
return self.rank == c.rank and self.suit == c.suit
suitRanks = dict( s = 4, h = 3, c = 2, d = 1 )
def __lt__( self, c ):
if self.rank < c.rank:
return True
elif self.rank == c.rank:
return Card.suitRanks[ self.suit ] < Card.suitRanks[ c.suit ]
else:
return False
paint = dict( t = 10, j = 11, q = 12, k = 13, a = 14 )
@staticmethod
def parse( s ):
assert len( s ) == 2, 'invalid card str %s' % s
rs = s[0]
if rs in Card.paint:
r = Card.paint[rs]
else:
r = int( rs )
return Card( r, s[1] )
class Hand:
def __init__( self, cards ):
assert len( cards ) == 5
self.cards = sorted( cards )
def __repr__( self ):
return str( self.cards )
def __lt__( self, h ):
ht, inv = self.getHandType()
hht, hinv = h.getHandType()
if ht < hht:
return True
elif ht == hht:
for c, hc in zip( sorted( inv, reverse = True ), sorted( hinv, reverse = True ) ):
if c < hc:
return True
elif c > hc:
return False
assert 0
else:
return False
@staticmethod
def parse( s ):
return Hand( map( Card.parse, s.lower().split() ) )
def getSets( self ):
sets = [[self.cards[0]]]
for card in self.cards[1:]:
if card.rank == sets[-1][-1].rank:
sets[-1].append( card )
else:
sets.append( [card] )
return sorted( sets, key = len, reverse = True )
def getSetsOfSize( self, n ):
return filter( lambda set: len( set ) == n, self.getSets() )
def fourOfAKind( self ):
sets = self.getSetsOfSize( 4 )
if sets:
return sets[0]
def twoPair( self ):
sets = self.getSetsOfSize( 2 )
if len( sets ) == 2:
return sum( sets, [] )
def pair( self ):
sets = self.getSetsOfSize( 2 )
if len( sets ) == 1:
return sets[0]
def threeOfAKind( self ):
sets = self.getSetsOfSize( 3 )
if sets:
return sets[0]
def fullHouse( self ):
sets = self.getSets()
if map( len, sets ) == [ 3, 2 ]:
return sum( sets, [] )
def flush( self ):
if all( [ self.cards[0].suit == card.suit for card in self.cards[1:] ] ):
return self.cards
def straight( self ):
if all( [ self.cards[i].rank + 1 == self.cards[i+1].rank for i in range( len( self.cards ) - 1 ) ] ):
return self.cards
def straightFlush( self ):
if self.straight() and self.flush():
return self.cards
def royalFlush( self ):
if self.straightFlush() and self.cards[0].rank == 10:
return self.cards
def highCard( self ):
return self.cards[-1:]
handTypes = [ royalFlush, straightFlush, fourOfAKind, fullHouse, flush, straight, threeOfAKind, twoPair, pair, highCard ]
def getHandType( self ):
for i, handType in enumerate( Hand.handTypes ):
inv = handType( self )
if inv:
return len( Hand.handTypes ) - i, inv
assert 0
@staticmethod
def getHandTypeName( i ):
return Hand.handTypes[ len( Hand.handTypes ) - i ].__name__
@staticmethod
def test():
handTypeData = [
( '2h 4c kd 8s ac', 'highCard', 'ac' ),
( '2h 2c 4c 6d 8s', 'pair', '2h 2c' ),
( '3h 3d 9s 9d kd', 'twoPair', '3h 3d 9s 9d' ),
( '2h 4h 4s 4d qd', 'threeOfAKind', '4h 4s 4d' ),
( '4h 5d 6c 7d 8s', 'straight', '' ),
( '2h 6h 7h 9h qh', 'flush', '' ),
( '6h 8d 8h 6s 6d', 'fullHouse', '' ),
( '8d 8h jd 8s 8c', 'fourOfAKind', '8h 8d 8c 8s' ),
( '7h 8h 9h th jh', 'straightFlush', '' ),
( 'ts js qs ks as', 'royalFlush', '' ),
]
for handStr, typeStr, involvedStr_ in handTypeData:
involvedStr = involvedStr_ or handStr
ht, involved = Hand.parse( handStr ).getHandType()
assert Hand.getHandTypeName( ht ) == typeStr
expInvolved = sorted( map( Card.parse, involvedStr.split() ) )
assert involved == expInvolved
compData = [
( '2h 4c kd 8s ac', '2h 4c kd 8s as', 1 ),
( '2h 4c kd 8s ac', '2h 2c kd 8s ac', 1 ),
]
for cd in compData:
expWin = cd[-1]
hands = map( Hand.parse, cd[:-1] )
win = max( range( len( hands ) ), key = hands.__getitem__ )
assert win == expWin, 'expected %s to win but %s won' % ( hands[expWin], hands[win] )
Hand.test()
wins = 0
for line in open( 'poker.txt' ).readlines():
toks = line.split()
h1 = Hand.parse( ' '.join( toks[:5] ) )
h2 = Hand.parse( ' '.join( toks[-5:] ) )
if h2 < h1:
wins += 1
return wins
def prob55():
def cond( n ):
i = 0
while i < 50:
n = n + int( str( n )[::-1] )
if isPalindrome( str( n ) ):
return False
i += 1
return True
assert not cond( 47 )
assert not cond( 349 )
assert cond( 4994 )
return sum( map( cond, range( 1, 10000 ) ) )
def prob56():
l = []
for a in range( 1, 100 ):
for b in range( 1, 100 ):
l.append( sum( map( int, str( a ** b ) ) ) )
return max( l )
def prob57():
def add( w, n, d ):
r = w * d + n, d
return r
def comp( l ):
n, d = 2, 1
for i in range( l - 1 ):
n, d = add( 2, d, n )
return add( 1, d, n )
assert map( comp, range( 1, 5 ) ) == [ ( 3, 2 ), ( 7, 5 ), ( 17, 12 ), ( 41, 29 ) ]
return sum( map( lambda (n,d): len( str( n ) ) > len( str( d ) ), map( comp, range( 1, 1001 ) ) ) )
def prob58():
@memoize
def getDiags( n ):
if n == 1:
return (1,), ()
else:
diags, primes = map( list, getDiags( n - 1 ) )
for i in range( 4 ):
diag = diags[-1] + ( n - 1 ) * 2
diags.append( diag )
if isPrime( diag ):
primes.append( diag )
return tuple( diags ), tuple( primes )
assert getDiags( 4 ) == ( ( 1, 3, 5, 7, 9, 13, 17, 21, 25, 31, 37, 43, 49 ), ( 3, 5, 7, 13, 17, 31, 37, 43 ) )
def getDiagPrimeFrac( n ):
diags, primes = getDiags( n )
return float( len( primes ) ) / float( len( diags ) )
i = 2
while getDiagPrimeFrac( i ) >= 0.1:
i += 1
return i * 2 - 1
def prob59():
def decrypt( key, cipherText ):
text = ''
ki = 0
for c in cipherText:
text += chr( c ^ ord( key[ki] ) )
ki = ( ki + 1 ) % len( key )
return text
def loadDict( pattern ):
import glob
d = set()
for filename in glob.glob( pattern ):
d = d.union( set( map( str.lower, open( filename ).read().split() ) ) )
return d
def genKeys( l ):
if l == 0:
return [ '' ]
else:
r = []
for base in [ chr( ord( 'a' ) + i ) for i in range( 26 ) ]:
for tail in genKeys( l - 1 ):
r.append( base + tail )
return r
d = loadDict( 'english*' )
lend = {}
for i in d:
l = len( i )
if l in lend:
lend[l].add( i )
else:
lend[l] = set( [i] )
cipherText = map( int, open( 'cipher1.txt' ).read().split(',') )
def numWords( text ):
nw = 0
for l, words in lend.iteritems():
for p in range( len( text ) - l ):
if text[p:p+l].lower() in words:
nw += 1
return nw
key = max( genKeys( 3 ), key = lambda k: numWords( decrypt( k, cipherText[:50] ) ) )
text = decrypt( key, cipherText )
return sum( map( ord, text ) )
def enumerateSubsets( l, n, unique = False ):
if n == 0:
return [[]]
elif len( l ) < n:
return []
else:
r = enumerateSubsets( l[1:], n )
for tail in enumerateSubsets( l[1:], n - 1 ):
r.append( l[:1] + tail )
return r
def prob60():
def cond( l, i ):
for j in l:
si = str( i )
sj = str( j )
if not isPrime( int( si + sj ) ) or not isPrime( int( sj + si ) ):
return False
return True
def search( l, currentSet, currentPos, n ):
if n == 0:
return currentSet
else:
for j in range( currentPos + 1, len( l ) - n ):
if cond( currentSet, l[j] ):
r = search( l, currentSet + [l[j]], j, n - 1 )
if r:
return r
primes = filter( isPrime, range( 1, 10000 ) )
assert [ 3, 7, 109, 673 ] == search( primes, [], 0, 4 )
return sum( search( primes, [], 0, 5 ) )
def inSeries( f, start = 1 ):
s = set([start])
li = [start]
def closure( n ):
while n > li[0]:
i = f( len( s ) + 1 )
li[0] = i
s.add( i )
return n in s
return closure
def prob61():
sers = [ inSeries( lambda n: n * ( n + 1 ) / 2 ),
inSeries( lambda n: n * n ),
inSeries( lambda n: n * ( 3 * n - 1 ) / 2 ),
inSeries( lambda n: n * ( 2 * n - 1 ) ),
inSeries( lambda n: n * ( 5 * n - 3 ) / 2 ),
inSeries( lambda n: n * ( 3 * n - 2 ) ),
]
def cond( l, cs ):
if not l:
return True
else:
for i in range( len( cs ) ):
if cs[i](l[0]):
return cond( l[1:], cs[:i] + cs[1+i:] )
return False
assert cond( [ 8128, 2882 ], sers[:4] )
assert cond( [ 8128, 2882, 8281 ], sers[:4] )
def convert( l ):
return [ int( l[i] + l[ ( i + 1 ) % len( l ) ] ) for i in range( len( l ) ) ]
def search( n, l, cs ):
ns = convert( l )
if cond( ns[:-1], cs ):
if not n:
if cond( ns, cs ):
return ns
else:
for i in range( 10, 100 ):
r = search( n - 1, l + [ str( i ) ], cs )
if r:
return r
assert sum( [ 8128, 2882, 8281 ] ) == sum( search( 3, [], sers[:4] ) )
return sum( search( 6, [], sers ) )
#slow
def prob62():
perms = []
i = 1
while True:
c = i ** 3
found = False
for perm in perms:
if isPermutation( str( perm[0] ), str( c ) ):
found = True
perm.append( c )
if len( perm ) == 5:
return min( perm )
if not found:
perms.append( [c] )
i += 1
def prob63():
n = 0
for i in range( 100 ):
j = 1
while len( str( j ** i ) ) < i:
j += 1
while len( str( j ** i ) ) == i:
j += 1
n += 1
return n
def getRootIndices( n, c ):
m = 0.
d = 1.
a0 = a = math.floor( math.sqrt( n ) )
f = [ int( a0 ) ]
for i in range( c - 1 ):
m = d * a - m
d = ( n - m * m ) / d
if not d: break
a = int( ( a0 + m ) / d )
f.append( a )
return f
def prob64():
def isCycle( l, n ):
return all( [ l[i*n:(i+1)*n] == l[:n] for i in range( 1, len( l ) / n ) ] )
def period( n ):
f = getRootIndices( n, 1001 )[1:]
if not f:
return 0
else:
return min( filter( lambda i: isCycle( f, i ), range( 1, len( f ) / 2 ) ) )
assert 4 == sum( map( lambda i: period( i ) % 2, range( 2, 14 ) ) )
return sum( map( lambda i: period( i ) % 2, range( 2, 10001 ) ) )
def prob65():
def calc( l ):
n, d = l[-1], 1
for j in l[:-1][::-1]:
n, d = add( j, d, n )
return n, d
l = [2] + sum( [ [ 1, i * 2, 1 ] for i in range( 1, 50 ) ], [] )
assert [ ( 2, 1 ),
( 3, 1 ),
( 8, 3 ),
( 11, 4 ),
( 19, 7 ) ] == [ calc( l[:i] ) for i in range( 1, 6 ) ]
def numSum( n ):
return sum( map( int, str( calc( l[:n] )[0] ) ) )
assert 17 == numSum( 10 )
return numSum( 100 )
def getConvergent( n, i ):
def add( w, n, d ):
r = w * d + n, d
return r
def calc( l ):
n, d = l[-1], 1
for j in l[:-1][::-1]:
n, d = add( j, d, n )
return n, d
return calc( getRootIndices( n, i ) )
def getConvergents( n, i ):
return [ getConvergent( n, j ) for j in range( 1, i + 1 ) ]
def prob66():
isSquare = inSeries( lambda n: n * n )
def solve( d ):
i = 1
while True:
x, y = getConvergent( d, i )
c = x * x - d * y * y
if c == 1:
return x
i += 1
assert [ 3, 2, 9, 5, 8 ] == map( solve, filter( lambda n: not isSquare( n ), range( 2, 8 ) ) )
return max( filter( lambda n: not isSquare( n ), range( 1, 1001 ) ), key = solve )
def prob67():
tri = [ map( int, line.split() ) for line in open( 'triangle.txt' ).readlines() ]
tri = tuple( map( tuple, tri ) )
@memoize
def triMaxSum2( tri, i, j ):
if i == len( tri ) - 1:
return tri[i][j]
else:
return tri[i][j] + max( triMaxSum2( tri, i + 1, j ), triMaxSum2( tri, i + 1, j + 1 ) )
return triMaxSum2( tri, 0, 0 )
def prob68():
def cond( ring ):
r0 = sum( ring[0] )
return all( [ r0 == sum( r ) for r in ring[1:] ] )
def toStr( ring ):
s = ''
i = min( range( len( ring ) ), key = lambda i: ring[i][0] )
for j in range( len( ring ) ):
s += ''.join( map( str, ring[ ( i + j ) % len( ring ) ] ) )
return s
def search( n, maxLen = None ):
res = set()
for perm in permute( range( 1, n * 2 + 1 ) ):
ring = []
for i in range( n ):
ring.append( ( perm[ i * 2 ], perm[ i * 2 + 1 ], perm[ ( ( i + 1 ) * 2 + 1 ) % len( perm ) ] ) )
if cond( ring ):
s = toStr( ring )
if not maxLen or len( s ) <= maxLen:
res.add( s )
return max( map( int, res ) )
assert 432621513 == search( 3 )
return search( 5, 16 )
def prob69():
def comp( n ):
lp = 1
p = 1
i = 1
while p < n:
while not isPrime( i ):
i += 1
lp = p
p *= i
i += 1
return lp
assert comp( 10 ) == 6
return comp( 1000000 )
def genPrimes( min, max ):
d = {}
q = 2
l = []
while q < max:
if q in d:
for p in d[q]:
d.setdefault( p + q, [] ).append( p )
d.pop( q )
else:
if q >= min:
l.append( q )
d[ q * q ] = [q]
q += 1
return l
def prob70():
max = 10 ** 7
root = int( math.sqrt( max ) )
primes = list( genPrimes( root / 2, root * 2 ) )
best = None
for i in range( len( primes ) ):
for j in range( i + 1, len( primes ) ):
n = primes[i] * primes[j]
if n <= max:
#doesn't work due to float accuracy
#p = int( n * product( [ 1 - 1 / float( k ) for k in ( primes[i], primes[j] ) ] ) )
p = ( primes[i] - 1 ) * ( primes[j] - 1 )
r = n / float( p )
if isPermutation( str( p ), str( n ) ) and ( best == None or r < best ):
best = r
bestn = n
return bestn
def prob71():
def comp( c ):
tn = 3
td = 7
bn = 0
bd = 1
for d in range( 1, c + 1 ):
fn = tn * d / float( td )
for n in range( int( fn ), int( fn ) + 2 ):
if n * td < tn * d and n * bd > bn * d:
bn = n
bd = d
return bn
assert comp( 8 ) == 2
return comp( 1000000 )
def prob72():
def comp( n ):
phi = range( n + 1 )
r = 0
for i in range( 2, n + 1 ):
if phi[i] == i:
for j in range( i, n + 1, i ):
o = phi[j]
phi[j] = int( phi[j] * ( 1 - 1 / float( i ) ) )
r += phi[i]
return r
assert comp( 8 ) == 21
return comp( 1000000 )
def gcd( a, b ):
while b:
a, b = b, a % b
return a
def prob73():
def comp( c ):
start = ( 1, 3 )
stop = ( 1, 2 )
r = 0
for d in range( 2, c + 1 ):
for n in range( int( start[0] * d / float( start[1] ) ), int( stop[0] * d / float( stop[1] ) ) + 2 ):
if n * start[1] > start[0] * d and n * stop[1] < stop[0] * d and gcd( n, d ) == 1:
r += 1
return r
assert comp( 8 ) == 3
return comp( 12000 )
def prob74():
facs = [ fac( i ) for i in range( 10 ) ]
def f( n ):
return sum( [ facs[ int( i ) ] for i in str( n ) ] )
def count( n ):
l = set([n])
i = f(n)
while i not in l:
l.add( i )
i = f( i )
return len( l )
assert f( 145 ) == 145
assert count( 540 ) == 2
assert count( 78 ) == 4
assert count( 69 ) == 5
return sum( [ count( i ) == 60 for i in range( 1000000 ) ] )
def prob75():
def e( m, n, k ):
m2 = m * m
n2 = n * n
return tuple( sorted( [ k * ( m2 - n2 ), k * 2 * m * n, k * ( m2 + n2 ) ] ) )
def gen( maxl ):
l = set()
m = 2
while True:
ll = len( l )
n = 1
while n < m:
k = 1
v = e( m, n, k )
while v not in l and sum( v ) < maxl:
l.add( v )
k += 1
v = e( m, n, k )
n += 1
if ll == len( l ):
break
m += 1
return l
def comp( n ):
d = {}
for v in gen( n ):
l = sum( v )
if l in d:
d[l] += 1
else:
d[l] = 1
return sum( [ v == 1 for v in d.itervalues() ] )
assert comp( 50 ) == 6
return comp( 1500000 )
def prob76():
@memoize
def comp( n, l = None ):
if n == 0:
return 1
else:
return sum( [ comp( n - i, i ) for i in range( 1, min( l or n - 1, n ) + 1 ) ] )
assert comp( 5 ) == 6
return comp( 100 )
def prob77():
primes = [2]
def primesTo( n ):
while primes[-1] < n:
i = primes[-1] + 1
while not isPrime( i ):
i += 1
primes.append( i )
l = []
i = 0
while i < len( primes ) and primes[i] <= n:
l.append( primes[i] )
i += 1
return l
@memoize
def comp( n, l = None ):
if n == 0:
return 1
else:
return sum( [ comp( n - i, i ) for i in primesTo( min( l or n, n ) ) ] )
assert comp( 10 ) == 5
i = 2
while comp( i ) < 5000:
i += 1
return i
def prob78():
def pent( n ):
return ( n * ( 3 * n - 1 ) ) / 2
def genPent( n ):
if n % 2:
return pent( -( n / 2 ) - 1 )
else:
return pent( ( n / 2 ) + 1 )
def sign( i ):
if i % 4 < 2:
return 1
else:
return -1
ps = [1]
n = 1
while True:
r = 0
i = 0
while True:
k = genPent( i )
if k > n:
break
r += sign( i ) * ps[n-k]
i += 1
if r % 1000000 == 0:
return n
ps.append( r )
if n == 5: assert r == 7
n += 1
def prob79():
ks = open( 'keylog.txt' ).read().split()
rels = set()
for k in ks:
for i in range( len( k ) - 1 ):
for j in range( i + 1, len( k ) ):
rels.add( k[i] + k[j] )
rels = list( rels )
def cond( s, ( l, r ), hard ):
if hard:
return l in s and r in s and s.index( l ) < s.rindex( r )
else:
return l not in s or r not in s or s.index( l ) < s.rindex( r )
l = ['']
while True:
for s in l:
if all( [ cond( s, rel, True ) for rel in rels ] ):
return s
nl = []
for s in l:
for i in map( str, range( 10 ) ):
if i not in s:
ns = s + i
if all( [ cond( s, rel, False ) for rel in rels ] ):
nl.append( ns )
assert nl
l = nl
def prob80():
isSquare = inSeries( lambda n: n * n )
def sqrt( n, digits ):
n *= 10 ** ( 2 * digits )
i = 0
j = 10 ** digits
while i != j:
i = j
j = ( i + ( n // i ) ) >> 1
return j
def comp( n ):
return sum( map( int, str( sqrt( n, 100 ) )[:100] ) )
assert comp( 2 ) == 475
return sum( [ comp( i ) for i in range( 1, 101 ) if not isSquare( i ) ] )
def prob81():
m = [ map( int, l.split( ',' ) ) for l in open( 'matrix.txt' ).readlines() ]
w = len( m[0] )
h = len( m )
minVal = min( map( min, m ) )
class Astar:
def __init__( self, i, j, parent ):
self.i = i
self.j = j
self.parent = parent
self.localCost = m[self.j][self.i]
self.costToTarget = ( w - self.i + h - self.j ) * minVal
self.calcCost()
def calcCost( self ):
self.travelCost = self.localCost
if self.parent:
self.travelCost += self.parent.travelCost
self.totalCost = self.travelCost + self.costToTarget
def expand( self ):
r = []
if self.i < w - 1:
r.append( Astar( self.i + 1, self.j, self ) )
if self.j < h - 1:
r.append( Astar( self.i, self.j + 1, self ) )
return r
def done( self ):
return self.i == w - 1 and self.j == h - 1
def samePos( self, n ):
return self.i == n.i and self.j == n.j
@staticmethod
def search( start ):
open = [ start ]
closed = []
while open:
next = min( open, key = lambda n: n.totalCost )
open.remove( next )
closed.append( next )
if next.done():
return next
else:
for child in next.expand():
if not any( [ child.samePos( n ) for n in closed ] ):
found = False
for n in open:
if child.samePos( n ):
found = True
if child.travelCost < n.travelCost:
n.parent = next
n.calcCost()
if not found:
open.append( child )
r = Astar.search( Astar( 0, 0, None ) ).travelCost
assert r == 427337, r
return r
m = [ map( int, line.split(',') ) for line in open( 'matrix.txt' ).readlines() ]
w = len( m[0] )
h = len( m )
@memoize
def comp( i, j ):
if i == w - 1 and j == h - 1:
return m[i][j]
else:
r = []
if i < w - 1:
r.append( m[i][j] + comp( i + 1, j ) )
if j < h - 1:
r.append( m[i][j] + comp( i, j + 1 ) )
return min( r )
r = comp( 0, 0 )
assert r == 427337
return r
def prob82():
m = [ map( int, l.split( ',' ) ) for l in open( 'matrix.txt' ).readlines() ]
# m = [ map( int, l.split() ) for l in '''131 673 234 103 18
# 201 96 342 965 150
# 630 803 746 422 111
# 537 699 497 121 956
# 805 732 524 37 331'''.split( '\n' ) ]
w = len( m[0] )
h = len( m )
minVal = min( map( min, m ) )
class Astar:
def __init__( self, i, j, parent ):
self.i = i
self.j = j
self.parent = parent
self.localCost = m[self.j][self.i]
self.costToTarget = ( w - self.i ) * minVal
self.calcCost()
def calcCost( self ):
self.travelCost = self.localCost
if self.parent:
self.travelCost += self.parent.travelCost
self.totalCost = self.travelCost + self.costToTarget
def expand( self ):
r = []
if self.i < w - 1:
r.append( Astar( self.i + 1, self.j, self ) )
if self.j < h - 1:
r.append( Astar( self.i, self.j + 1, self ) )
if self.j > 0:
r.append( Astar( self.i, self.j - 1, self ) )
return r
def done( self ):
return self.i == w - 1
def samePos( self, n ):
return self.i == n.i and self.j == n.j
@staticmethod
def search( start ):
open = start
closed = []
while open:
next = min( open, key = lambda n: n.totalCost )
open.remove( next )
closed.append( next )
if next.done():
return next
else:
for child in next.expand():
if not any( [ child.samePos( n ) for n in closed ] ):
found = False
for n in open:
if child.samePos( n ):
found = True
if child.travelCost < n.travelCost:
n.parent = next
n.calcCost()
if not found:
open.append( child )
return Astar.search( [ Astar( 0, j, None ) for j in range( h ) ] ).travelCost
def prob83():
m = [ map( int, l.split( ',' ) ) for l in open( 'matrix.txt' ).readlines() ]
w = len( m[0] )
h = len( m )
minVal = min( map( min, m ) )
class Astar:
def __init__( self, i, j, parent ):
self.i = i
self.j = j
self.parent = parent
self.localCost = m[self.j][self.i]
self.costToTarget = ( w - self.i + h - self.j ) * minVal
self.calcCost()
def calcCost( self ):
self.travelCost = self.localCost
if self.parent:
self.travelCost += self.parent.travelCost
self.totalCost = self.travelCost + self.costToTarget
def expand( self ):
r = []
if self.i < w - 1:
r.append( Astar( self.i + 1, self.j, self ) )
if self.i > 0:
r.append( Astar( self.i - 1, self.j, self ) )
if self.j < h - 1:
r.append( Astar( self.i, self.j + 1, self ) )
if self.j > 0:
r.append( Astar( self.i, self.j - 1, self ) )
return r
def done( self ):
return self.i == w - 1 and self.j == h - 1
def samePos( self, n ):
return self.i == n.i and self.j == n.j
@staticmethod
def search( start ):
open = [ start ]
closed = []
while open:
next = min( open, key = lambda n: n.totalCost )
open.remove( next )
closed.append( next )
if next.done():
return next
else:
for child in next.expand():
if not any( [ child.samePos( n ) for n in closed ] ):
found = False
for n in open:
if child.samePos( n ):
found = True
if child.travelCost < n.travelCost:
n.parent = next
n.calcCost()
if not found:
open.append( child )
return Astar.search( Astar( 0, 0, None ) ).travelCost
def prob84():
import random
board = '''
GO A1 CC1 A2 T1 R1 B1 CH1 B2 B3
JAIL C1 U1 C2 C3 R2 D1 CC2 D2 D3
FP E1 CH2 E2 E3 R3 F1 F2 U2 F3
G2J G1 G2 CC3 G3 R4 CH3 H1 T2 H2
'''.split()
def comp( dieSize, n ):
i = 0
c = [ 0 ] * len( board )
for r in range( n ):
i = ( i + random.randint( 1, dieSize ) + random.randint( 1, dieSize ) ) % len( board )
if board[i] == 'G2J':
i = board.index( 'JAIL' )
elif board[i].startswith( 'CC' ):
j = random.randint( 1, 16 )
if j == 1:
i = board.index( 'GO' )
elif j == 2:
i = board.index( 'JAIL' )
elif board[i].startswith( 'CH' ):
j = random.randint( 1, 16 )
if j == 1:
i = board.index( 'GO' )
elif j == 2:
i = board.index( 'JAIL' )
elif j == 3:
i = board.index( 'C1' )
elif j == 4:
i = board.index( 'E3' )
elif j == 5:
i = board.index( 'H2' )
elif j == 6:
i = board.index( 'R1' )
elif j == 7 or j == 8:
while not board[i].startswith( 'R' ):
i = ( i + 1 ) % len( board )
elif j == 9:
while not board[i].startswith( 'U' ):
i = ( i + 1 ) % len( board )
elif j == 10:
i -= 3
c[i] += 1
return ''.join( [ '%02d' % i for i in sorted( range( len( c ) ), key = c.__getitem__, reverse = True )[:3] ] )
n = 1000000
assert comp( 6, n ) == '102400'
return comp( 4, n )
def prob85():
def comp( w, h ):
r = 0
for i in range( 1, w + 1 ):
for j in range( 1, h + 1 ):
r += ( w + 1 - i ) * ( h + 1 - j )
return r
assert 18 == comp( 3, 2 )
mind = None
for w in range( 1, 100 ):
for h in range( 1, 100 ):
c = comp( w, h )
d = abs( 2000000 - c )
if not mind or d < mind:
mind = d
mina = w * h
return mina
def prob86():
isSquare = inSeries( lambda n: n * n )
l = 1
c = 0
while True:
for wh in range( 3, 2 * l + 1 ):
if isSquare( l * l + wh * wh ):
if wh <= l:
c += wh / 2
else:
d = 1 + ( l - ( wh + 1 ) / 2 )
c += d
if c > 1000000:
return l
l += 1
def prob87():
def comp( n ):
primes = {}
primes[2] = filter( isPrime, range( 2, int( math.sqrt( n ) ) + 1 ) )
primes[3] = filter( lambda p: p <= int( n ** ( 1 / 3. ) ), primes[2] )
primes[4] = filter( lambda p: p <= int( n ** ( 1 / 4. ) ), primes[3] )
s = set()
for p4 in primes[4]:
for p3 in primes[3]:
for p2 in primes[2]:
v = p4 ** 4 + p3 ** 3 + p2 ** 2
if v <= n:
s.add( v )
return len( s )
assert comp( 50 ) == 4
return comp( 50000000 )
def prob88():
d = {}
def calc( n, nf, l ):
if len( l ) <= nf:
i = 2
p = product( l )
s = sum( l )
ll = len( l )
np = p * i
while np < n * 2:
if ll >= 1:
ns = s + i
nl = ll + 1 + np - ns
if nl <= n and ( not nl in d or ( nl in d and np < d[nl] ) ):
d[nl] = np
calc( n, nf, l + [ i ] )
i += 1
np = p * i
def comp( n ):
calc( n, int( math.log( n, 2 ) ), [] )
return sum( set( d.values() ) )
assert 61 == comp( 12 )
return comp( 12000 )
if __name__ == '__main__':
import sys, time
assert len( sys.argv ) == 2, 'usage: %s <probnum>' % sys.argv[0]
probnum = int( sys.argv[1] )
fname = 'prob%d' % probnum
assert fname in globals(), 'unknown probnum %d' % probnum
f = globals()[fname]
start = time.time()
sol = f()
print 'prob %d solution is' % probnum, sol
t = time.time() - start
print 'solution took %f secs' % t
assert t < 60, 'prob %d took %f secs' % ( probnum, t )
| Python |
from copy import copy
import sys
class GameState:
def expand( self ):
raise RuntimeError
def apply( self, move ):
raise RuntimeError
def eval( self ):
raise RuntimeError
def getWinner( self ):
raise RuntimeError
def getPlayer( self ):
raise RuntimeError
class Game:
def __init__( self, playerTypes, **moves ):
self.playerTypes = playerTypes
self.moves = moves
self.moves[ 'minimax' ] = self.minimaxMove
self.moves[ 'collect' ] = self.collectMove
self.moves[ 'int' ] = self.intMove
self.moves[ 'console' ] = self.consoleMove
def run( self, state ):
while not state.getWinner():
player = state.getPlayer()
assert player in self.playerTypes, 'unknown player %s' % player
playerType = self.playerTypes[ player ]
assert playerType in self.moves, 'unknown playerType %s' % playerType
state = self.moves[ playerType ]( state )
return state
def expand( self, state ):
return map( state.apply, state.expand() )
def minimax( self, state, ply ):
if state.getWinner() or ply <= 0:
return state.eval()
else:
return max( [ -sys.maxint ] + [ -self.minimax( child, ply - 1 ) for child in self.expand( state ) ] )
def minimaxMove( self, state ):
return max( self.expand( state ), key = lambda child: self.minimax( child, 4 ) )
def collect( self, state, player, ply ):
score = state.eval()
if state.getPlayer() == player:
score *= -1
scores = [ score ]
if not state.getWinner() and ply > 0:
for child in self.expand( state ):
scores += self.collect( child, player, ply - 1 )
return scores
def collectMove( self, state ):
return max( self.expand( state ), key = lambda child: sum( self.collect( child, state.getPlayer(), 2 ) ) )
def stats( self, scores ):
ave = sum( scores ) / float( len( scores ) )
dev = sum( [ abs( score - ave ) for score in scores ] ) / float( len( scores ) )
return ave, dev
def intMove( self, state ):
def eval( child ):
scores = self.collect( child, state.getPlayer(), 2 )
ave, dev = self.stats( scores )
score = dev + ave * abs( ave )
return score
return max( self.expand( state ), key = eval )
def consoleMove( self, state ):
moves = state.expand()
print 'current state:'
print state
print 'moves:'
for i, move in enumerate( moves ):
print '%d: %s' % ( i, move )
return state.apply( moves[ input( 'enter move index: ' ) ] )
class ToeMove:
def __init__( self, i, j, player ):
self.i = i
self.j = j
self.player = player
def __repr__( self ):
return 'move player %s to %d %d' % ( self.player, self.i, self.j )
class Toe( GameState ):
lines = {}
def __init__( self, w = 3, h = 3 ):
self.player = 'x'
self.w = w
self.h = h
self.board = [ ' ' ] * self.w * self.h
def __getitem__( self, i ):
return self.board[ i[0] * self.w + i[1] ]
def __setitem__( self, i, val ):
self.board[ i[0] * self.w + i[1] ] = val
def __repr__( self ):
s = ' 0 1 2\n'
for i in range( self.h ):
s += '%d ' % i
for j in range( self.w ):
s += self[j,i]
if j < 2:
s += '|'
elif i < 2:
s += '\n'
if i < 2:
s += ' -+-+-\n'
return s
@staticmethod
def otherPlayer( player ):
if player == 'x':
return 'o'
elif player == 'o':
return 'x'
else:
raise ValueError( player )
def expand( self ):
moves = []
for i in range( self.w ):
for j in range( self.h ):
if self[i,j] == ' ':
moves.append( ToeMove( i, j, self.player ) )
return moves
def apply( self, move ):
state = Toe()
state.board = copy( self.board )
state[move.i,move.j] = move.player
state.player = Toe.otherPlayer( move.player )
return state
def getWinner( self ):
win = min( self.w, self.h )
if self.countLines( win, win, self.player ):
return self.player
elif self.countLines( win, win, Toe.otherPlayer( self.player ) ):
return Toe.otherPlayer( self.player )
elif all( [ val != ' ' for val in self.board ] ):
return 'tie'
def eval( self ):
otherPlayer = self.player
player = Toe.otherPlayer( otherPlayer )
score = 0
win = min( self.w, self.h )
for p, mult in [ ( player, 1 ), ( otherPlayer, -1 ) ]:
for i in range( 1, win + 1 ):
score += 10 ** ( i - 1 ) * self.countLines( win, i, p )
return score
@staticmethod
def countLines( self, length, count, player ):
key = length, count, player, ''.join( self.board )
if key in Toe.lines:
return Toe.lines[key]
numLines = 0
otherPlayer = self.otherPlayer( player )
for i in range( self.w ):
for j in range( self.h ):
for di in range( -1, 2 ):
for dj in range( -1, 2 ):
maxi = i + di * ( length - 1 )
maxj = j + dj * ( length - 1 )
if ( di or dj ) and maxi >= 0 and maxi < self.w and maxj >= 0 and maxj < self.h:
numMatch = 0
numOther = 0
for k in range( length ):
val = self[ i + di * k, j + dj * k ]
if val == player:
numMatch += 1
elif val == otherPlayer:
numOther += 1
if numMatch >= count and numOther == 0:
numLines += 1
Toe.lines[key] = numLines
return numLines
def getPlayer( self ):
return self.player
class ConnectFourMove:
def __init__( self, player, i ):
self.player = player
self.i = i
def __repr__( self ):
return 'Add %s to column %d' % ( self.player, self.i )
class ConnectFour:
def __init__( self, w = 10, h = 5 ):
self.w = w
self.h = h
self.board = [ ' ' ] * self.w * self.h
self.player = 'r'
def __getitem__( self, ( i, j ) ):
return self.board[ j * self.w + i ]
def __setitem__( self, ( i, j ), val ):
self.board[ j * self.w + i ] = val
def __repr__( self ):
s = ''
for i in range( self.w ):
s += '%d ' % i
s += '\n'
for j in range( self.h ):
for i in range( self.w ):
s += self[i,j]
if i < self.w - 1:
s += '|'
s += '\n'
s += '-+' * ( self.w - 1 ) + '-'
return s
def colheight( self, i ):
j = 0
while j < self.h and self[ i, self.h - 1 - j ] != ' ':
j += 1
return j
def expand( self ):
moves = []
for i in range( self.w ):
if self.colheight( i ) < self.h:
moves.append( ConnectFourMove( self.player, i ) )
return moves
def apply( self, move ):
j = self.colheight( move.i )
assert j < self.h
cf = ConnectFour( self.w, self.h )
cf.board = [ val for val in self.board ]
cf[ move.i, self.h - 1 - j ] = move.player
cf.player = self.otherPlayer( self.player )
return cf
@staticmethod
def otherPlayer( player ):
if player == 'r':
return 'b'
else:
return 'r'
def eval( self ):
otherPlayer = self.player
player = ConnectFour.otherPlayer( otherPlayer )
score = 0
for p, m in [ ( player, 1 ), ( otherPlayer, -1 ) ]:
for i in range( 1, 5 ):
score += 10 ** ( i - 1 ) * Toe.countLines( self, 4, i, p )
return score
def getWinner( self ):
otherPlayer = ConnectFour.otherPlayer( self.player )
if Toe.countLines( self, 4, 4, self.player ):
return self.player
elif Toe.countLines( self, 4, 4, otherPlayer ):
return otherPlayer
elif all( [ val != ' ' for val in self.board ] ):
return 'tie'
def getPlayer( self ):
return self.player
if __name__ == '__main__':
final = Game( { 'r': 'console', 'b': 'minimax' } ).run( ConnectFour() )
print final
print 'winner:', final.getWinner()
| Python |
#factory
n = Node( "core", "Node" )
assert 'Node' == n.type
#tree
child = Node( "core", "Node" )
n.addChild( child )
assert n == child.parent
assert n.hasChild( child )
assert [ child ] == n.children
n.removeChild( child )
assert not n.hasChild( child )
assert [] == n.children
assert None == child.parent
child.attachToParent( n )
assert n == child.parent
assert n.hasChild( child )
assert [ child ] == n.children
child.detachFromParent()
assert None == child.parent
assert not n.hasChild( child )
assert [] == n.children
#node subclass
@node( "pytest" )
class PyTestNode:
def __init__( self ):
self.i = 0
self.jval = 0
def foo( self, i ):
self.i = i
def bar( self ):
return self.i
def set_j( self, j ):
self.jval = j
def get_j( self ):
return self.jval
def get_k( self ):
return 3
testNode = Node( "pytest", 'PyTestNode' )
assert testNode.module == "pytest"
assert testNode.type == 'PyTestNode'
assert 0 == testNode.i
testNode.i = -1
assert -1 == testNode.i
assert -1 == testNode.bar()
testNode.foo( 1 )
assert 1 == testNode.bar()
assert 0 == testNode.j
testNode.j = 2
assert 2 == testNode.j
assert 3 == testNode.k
#math
def eq( d1, d2 ):
return abs( d1 - d2 ) < 1e-5
import math
rr = Rot2d.fromRadians( math.pi )
assert eq( 180, rr.degrees() )
assert eq( math.pi, rr.radians() )
rd = Rot2d.fromDegrees( 180 )
assert eq( 180, rd.degrees() )
assert eq( math.pi, rd.radians() )
assert rr == rd
assert Rot2d.fromDegrees( 90 ) + Rot2d.fromRadians( math.pi / 4 ) == Rot2d.fromDegrees( 135 )
assert Rot2d.fromDegrees( 180 ) - Rot2d.fromDegrees( 90 ) == Rot2d.fromRadians( math.pi / 2 )
assert Rot2d.fromDegrees( -45 ) == Rot2d.fromDegrees( 45 ).inverse()
v = Vec2d( 1, 2 )
assert v == v
assert 1 == v.x
assert 2 == v.y
t = Vec2d( 3, 4 )
assert Vec2d( v.x + t.x, v.y + t.y ) == v + t
assert Vec2d( v.x - t.x, v.y - t.y ) == v - t
assert Vec2d( v.x * t.x, v.y * t.y ) == v * t
assert Vec2d( v.x / t.x, v.y / t.y ) == v / t
assert Vec2d( v.x * 3, v.y * 3 ) == v * 3
assert Vec2d( v.x / 2, v.y / 2 ) == v / 2
assert t.squaredLength() == 25
assert t.length() == 5
assert Vec2d( 0, 1 ).toRot() == Rot2d.fromDegrees( 90 )
assert Vec2d( 10, 0 ).normalize() == Vec2d( 1, 0 )
assert Vec2d( 20, 10 ).dot( Vec2d( 1, 2 ) ) == 40
axis = Vec3d( 1, 2, 3 )
angle = 0.45
r = Rot3d( axis, angle )
assert axis.normalize(), angle == r.toAxisAngle()
assert Vec3d( 0, 1, 0 ) == Rot3d( Vec3d( 0, 0, 1 ), math.pi / 2. ) * Vec3d( 1, 0, 0 )
assert Rot3d( Vec3d( 0, 0, 1 ), math.pi / 4. ) == Rot3d( Vec3d( 0, 0, -1 ), math.pi / 4. ).inverse()
v = Vec2d( 1, 2 )
t = Vec2d( 3, 4 )
r = Rot2d.fromDegrees( 5 )
s = Vec2d( 5, 6 )
mt = Mat2d.translation( t )
mr = Mat2d.rotation( r )
ms = Mat2d.scale( s )
assert t == mt.getTranslation()
assert r == mr.getRotation()
assert s == ms.getScale()
assert v == Mat2d() * v
assert v + t == mt * v
assert v * r == mr * v
assert v * s == ms * v
assert s * ( ( t + v ) * r ) == ms * ( mr * ( mt * v ) )
assert s * ( ( t + v ) * r ) == ( ms * mr * mt ) * v
mti = mt.inverse()
mri = mr.inverse()
msi = ms.inverse()
ri = r.inverse()
assert v == v * r * ri
assert v - t == mti * v
assert v * ri == mri * v
assert v / s == msi * v
assert ( ( v - t ) * ri ) / s == msi * ( mri * ( mti * v ) )
assert ( ( v - t ) * ri ) / s == ( msi * mri * mti ) * v
v = Vec3d( 1, 2, 3 )
t = Vec3d( 3, 4, 5 )
r = Rot3d( Vec3d( -1, -2, -3 ), -.4 )
s = Vec3d( 5, 6, 7 )
mt = Mat3d.translation( t )
mr = Mat3d.rotation( r )
ms = Mat3d.scale( s )
assert t == mt.getTranslation()
assert r == mr.getRotation()
assert s == ms.getScale()
assert v == Mat3d() * v
assert v + t == mt * v
assert v * r == mr * v
assert v * s == ms * v
assert s * ( ( t + v ) * r ) == ms * ( mr * ( mt * v ) )
assert s * ( ( t + v ) * r ) == ( ms * mr * mt ) * v
mti = mt.inverse()
mri = mr.inverse()
msi = ms.inverse()
ri = r.inverse()
assert v == v * r * ri
assert v - t == mti * v
assert v * ri == mri * v
assert v / s == msi * v
assert ( ( v - t ) * ri ) / s == msi * ( mri * ( mti * v ) )
assert ( ( v - t ) * ri ) / s == ( msi * mri * mti ) * v
| Python |
import sys
import os
filename = '%s/include/gtest/gtest.h' % sys.argv[1]
orig = open( filename, 'r' ).read()
os.remove( filename )
open( filename, 'w' ).write( '#define GTEST_HAS_TR1_TUPLE 0\n%s' % orig )
| Python |
@self.func
def update( self, t, dt ):
print self.parent.position
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
if size > 0:
size = round(size/1024)
if size < 1:
size = 1
files += """<File name="%s" size="%d" />""" % (
convertToXmlAttribute(someObject),
size
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
# Check for invalid folder paths (..)
if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ):
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
import os
try: # Windows needs stdio set for binary mode for file upload to work.
import msvcrt
msvcrt.setmode (0, os.O_BINARY) # stdin = 0
msvcrt.setmode (1, os.O_BINARY) # stdout = 1
except ImportError:
pass
from fckutil import *
from fckoutput import *
import config as Config
class GetFoldersCommandMixin (object):
def getFolders(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
s = """<Folders>""" # Open the folders node
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
s += """</Folders>""" # Close the folders node
return s
class GetFoldersAndFilesCommandMixin (object):
def getFoldersAndFiles(self, resourceType, currentFolder):
"""
Purpose: command to recieve a list of folders and files
"""
# Map the virtual path to our local server
serverPath = mapServerFolder(self.userFilesFolder,currentFolder)
# Open the folders / files node
folders = """<Folders>"""
files = """<Files>"""
for someObject in os.listdir(serverPath):
someObjectPath = mapServerFolder(serverPath, someObject)
if os.path.isdir(someObjectPath):
folders += """<Folder name="%s" />""" % (
convertToXmlAttribute(someObject)
)
elif os.path.isfile(someObjectPath):
size = os.path.getsize(someObjectPath)
if size > 0:
size = round(size/1024)
if size < 1:
size = 1
files += """<File name="%s" size="%d" />""" % (
convertToXmlAttribute(someObject),
size
)
# Close the folders / files node
folders += """</Folders>"""
files += """</Files>"""
return folders + files
class CreateFolderCommandMixin (object):
def createFolder(self, resourceType, currentFolder):
"""
Purpose: command to create a new folder
"""
errorNo = 0; errorMsg ='';
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
newFolder = sanitizeFolderName (newFolder)
try:
newFolderPath = mapServerFolder(self.userFilesFolder, combinePaths(currentFolder, newFolder))
self.createServerFolder(newFolderPath)
except Exception, e:
errorMsg = str(e).decode('iso-8859-1').encode('utf-8') # warning with encodigns!!!
if hasattr(e,'errno'):
if e.errno==17: #file already exists
errorNo=0
elif e.errno==13: # permission denied
errorNo = 103
elif e.errno==36 or e.errno==2 or e.errno==22: # filename too long / no such file / invalid name
errorNo = 102
else:
errorNo = 110
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def createServerFolder(self, folderPath):
"Purpose: physically creates a folder on the server"
# No need to check if the parent exists, just create all hierachy
try:
permissions = Config.ChmodOnFolderCreate
if not permissions:
os.makedirs(folderPath)
except AttributeError: #ChmodOnFolderCreate undefined
permissions = 0755
if permissions:
oldumask = os.umask(0)
os.makedirs(folderPath,mode=0755)
os.umask( oldumask )
class UploadFileCommandMixin (object):
def uploadFile(self, resourceType, currentFolder):
"""
Purpose: command to upload files to server (same as FileUpload)
"""
errorNo = 0
if self.request.has_key("NewFile"):
# newFile has all the contents we need
newFile = self.request.get("NewFile", "")
# Get the file name
newFileName = newFile.filename
newFileName = sanitizeFileName( newFileName )
newFileNameOnly = removeExtension(newFileName)
newFileExtension = getExtension(newFileName).lower()
allowedExtensions = Config.AllowedExtensions[resourceType]
deniedExtensions = Config.DeniedExtensions[resourceType]
if (allowedExtensions):
# Check for allowed
isAllowed = False
if (newFileExtension in allowedExtensions):
isAllowed = True
elif (deniedExtensions):
# Check for denied
isAllowed = True
if (newFileExtension in deniedExtensions):
isAllowed = False
else:
# No extension limitations
isAllowed = True
if (isAllowed):
# Upload to operating system
# Map the virtual path to the local server path
currentFolderPath = mapServerFolder(self.userFilesFolder, currentFolder)
i = 0
while (True):
newFilePath = os.path.join (currentFolderPath,newFileName)
if os.path.exists(newFilePath):
i += 1
newFileName = "%s(%d).%s" % (
newFileNameOnly, i, newFileExtension
)
errorNo= 201 # file renamed
else:
# Read file contents and write to the desired path (similar to php's move_uploaded_file)
fout = file(newFilePath, 'wb')
while (True):
chunk = newFile.file.read(100000)
if not chunk: break
fout.write (chunk)
fout.close()
if os.path.exists ( newFilePath ):
doChmod = False
try:
doChmod = Config.ChmodOnUpload
permissions = Config.ChmodOnUpload
except AttributeError: #ChmodOnUpload undefined
doChmod = True
permissions = 0755
if ( doChmod ):
oldumask = os.umask(0)
os.chmod( newFilePath, permissions )
os.umask( oldumask )
newFileUrl = combinePaths(self.webUserFilesFolder, currentFolder) + newFileName
return self.sendUploadResults( errorNo , newFileUrl, newFileName )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "" )
else:
return self.sendUploadResults( errorNo = 202, customMsg = "No File" )
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = "/"
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
if (command == "FileUpload"):
return self.sendUploadResults( errorNo = 102, customMsg = "" )
else:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
if number != 1:
return """<Error number="%s" />""" % (number)
else:
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2009 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*
* Configuration file for the File Manager Connector for Python
"""
# INSTALLATION NOTE: You must set up your server environment accordingly to run
# python scripts. This connector requires Python 2.4 or greater.
#
# Supported operation modes:
# * WSGI (recommended): You'll need apache + mod_python + modpython_gateway
# or any web server capable of the WSGI python standard
# * Plain Old CGI: Any server capable of running standard python scripts
# (although mod_python is recommended for performance)
# This was the previous connector version operation mode
#
# If you're using Apache web server, replace the htaccess.txt to to .htaccess,
# and set the proper options and paths.
# For WSGI and mod_python, you may need to download modpython_gateway from:
# http://projects.amor.org/misc/svn/modpython_gateway.py and copy it in this
# directory.
# SECURITY: You must explicitly enable this "connector". (Set it to "True").
# WARNING: don't just set "ConfigIsEnabled = True", you must be sure that only
# authenticated users can access this file or use some kind of session checking.
Enabled = False
# Path to user files relative to the document root.
UserFilesPath = '/userfiles/'
# Fill the following value it you prefer to specify the absolute path for the
# user files directory. Useful if you are using a virtual directory, symbolic
# link or alias. Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'UserFilesPath' must point to the same directory.
# WARNING: GetRootPath may not work in virtual or mod_python configurations, and
# may not be thread safe. Use this configuration parameter instead.
UserFilesAbsolutePath = ''
# Due to security issues with Apache modules, it is recommended to leave the
# following setting enabled.
ForceSingleExtension = True
# What the user can do with this connector
ConfigAllowedCommands = [ 'QuickUpload', 'FileUpload', 'GetFolders', 'GetFoldersAndFiles', 'CreateFolder' ]
# Allowed Resource Types
ConfigAllowedTypes = ['File', 'Image', 'Flash', 'Media']
# After file is uploaded, sometimes it is required to change its permissions
# so that it was possible to access it at the later time.
# If possible, it is recommended to set more restrictive permissions, like 0755.
# Set to 0 to disable this feature.
# Note: not needed on Windows-based servers.
ChmodOnUpload = 0755
# See comments above.
# Used when creating folders that does not exist.
ChmodOnFolderCreate = 0755
# Do not touch this 3 lines, see "Configuration settings for each Resource Type"
AllowedExtensions = {}; DeniedExtensions = {};
FileTypesPath = {}; FileTypesAbsolutePath = {};
QuickUploadPath = {}; QuickUploadAbsolutePath = {};
# Configuration settings for each Resource Type
#
# - AllowedExtensions: the possible extensions that can be allowed.
# If it is empty then any file type can be uploaded.
# - DeniedExtensions: The extensions that won't be allowed.
# If it is empty then no restrictions are done here.
#
# For a file to be uploaded it has to fulfill both the AllowedExtensions
# and DeniedExtensions (that's it: not being denied) conditions.
#
# - FileTypesPath: the virtual folder relative to the document root where
# these resources will be located.
# Attention: It must start and end with a slash: '/'
#
# - FileTypesAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'FileTypesPath' must point to the same directory.
# Attention: It must end with a slash: '/'
#
#
# - QuickUploadPath: the virtual folder relative to the document root where
# these resources will be uploaded using the Upload tab in the resources
# dialogs.
# Attention: It must start and end with a slash: '/'
#
# - QuickUploadAbsolutePath: the physical path to the above folder. It must be
# an absolute path.
# If it's an empty string then it will be autocalculated.
# Useful if you are using a virtual directory, symbolic link or alias.
# Examples: 'C:\\MySite\\userfiles\\' or '/root/mysite/userfiles/'.
# Attention: The above 'QuickUploadPath' must point to the same directory.
# Attention: It must end with a slash: '/'
AllowedExtensions['File'] = ['7z','aiff','asf','avi','bmp','csv','doc','fla','flv','gif','gz','gzip','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','ods','odt','pdf','png','ppt','pxd','qt','ram','rar','rm','rmi','rmvb','rtf','sdc','sitd','swf','sxc','sxw','tar','tgz','tif','tiff','txt','vsd','wav','wma','wmv','xls','xml','zip']
DeniedExtensions['File'] = []
FileTypesPath['File'] = UserFilesPath + 'file/'
FileTypesAbsolutePath['File'] = (not UserFilesAbsolutePath == '') and (UserFilesAbsolutePath + 'file/') or ''
QuickUploadPath['File'] = FileTypesPath['File']
QuickUploadAbsolutePath['File'] = FileTypesAbsolutePath['File']
AllowedExtensions['Image'] = ['bmp','gif','jpeg','jpg','png']
DeniedExtensions['Image'] = []
FileTypesPath['Image'] = UserFilesPath + 'image/'
FileTypesAbsolutePath['Image'] = (not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'image/' or ''
QuickUploadPath['Image'] = FileTypesPath['Image']
QuickUploadAbsolutePath['Image']= FileTypesAbsolutePath['Image']
AllowedExtensions['Flash'] = ['swf','flv']
DeniedExtensions['Flash'] = []
FileTypesPath['Flash'] = UserFilesPath + 'flash/'
FileTypesAbsolutePath['Flash'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'flash/' or ''
QuickUploadPath['Flash'] = FileTypesPath['Flash']
QuickUploadAbsolutePath['Flash']= FileTypesAbsolutePath['Flash']
AllowedExtensions['Media'] = ['aiff','asf','avi','bmp','fla', 'flv','gif','jpeg','jpg','mid','mov','mp3','mp4','mpc','mpeg','mpg','png','qt','ram','rm','rmi','rmvb','swf','tif','tiff','wav','wma','wmv']
DeniedExtensions['Media'] = []
FileTypesPath['Media'] = UserFilesPath + 'media/'
FileTypesAbsolutePath['Media'] = ( not UserFilesAbsolutePath == '') and UserFilesAbsolutePath + 'media/' or ''
QuickUploadPath['Media'] = FileTypesPath['Media']
QuickUploadAbsolutePath['Media']= FileTypesAbsolutePath['Media']
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Base Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import cgi, os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
import config as Config
class FCKeditorConnectorBase( object ):
"The base connector class. Subclass it to extend functionality (see Zope example)"
def __init__(self, environ=None):
"Constructor: Here you should parse request fields, initialize variables, etc."
self.request = FCKeditorRequest(environ) # Parse request
self.headers = [] # Clean Headers
if environ:
self.environ = environ
else:
self.environ = os.environ
# local functions
def setHeader(self, key, value):
self.headers.append ((key, value))
return
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, environ):
if environ: # WSGI
self.request = cgi.FieldStorage(fp=environ['wsgi.input'],
environ=environ,
keep_blank_values=1)
self.environ = environ
else: # plain old cgi
self.environ = os.environ
self.request = cgi.FieldStorage()
if 'REQUEST_METHOD' in self.environ and 'QUERY_STRING' in self.environ:
if self.environ['REQUEST_METHOD'].upper()=='POST':
# we are in a POST, but GET query_string exists
# cgi parses by default POST data, so parse GET QUERY_STRING too
self.get_request = cgi.FieldStorage(fp=None,
environ={
'REQUEST_METHOD':'GET',
'QUERY_STRING':self.environ['QUERY_STRING'],
},
)
else:
self.get_request={}
def has_key(self, key):
return self.request.has_key(key) or self.get_request.has_key(key)
def get(self, key, default=None):
if key in self.request.keys():
field = self.request[key]
elif key in self.get_request.keys():
field = self.get_request[key]
else:
return default
if hasattr(field,"filename") and field.filename: #file upload, do not convert return value
return field
else:
return field.value
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
See config.py for configuration settings
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckoutput import * # base http, xml and html output mixins
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorConnector( FCKeditorConnectorBase,
GetFoldersCommandMixin,
GetFoldersAndFilesCommandMixin,
CreateFolderCommandMixin,
UploadFileCommandMixin,
BaseHttpMixin, BaseXmlMixin, BaseHtmlMixin ):
"The Standard connector class."
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
s = ""
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendError(1, "This connector is disabled. Please check the connector configurations in \"editor/filemanager/connectors/py/config.py\" and try again.")
# Make sure we have valid inputs
for key in ("Command","Type","CurrentFolder"):
if not self.request.has_key (key):
return
# Get command, resource type and current folder
command = self.request.get("Command")
resourceType = self.request.get("Type")
currentFolder = getCurrentFolder(self.request.get("CurrentFolder"))
# Check for invalid paths
if currentFolder is None:
if (command == "FileUpload"):
return self.sendUploadResults( errorNo = 102, customMsg = "" )
else:
return self.sendError(102, "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendError( 1, 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendError( 1, 'Invalid type specified' )
# Setup paths
if command == "QuickUpload":
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
else:
self.userFilesFolder = Config.FileTypesAbsolutePath[resourceType]
self.webUserFilesFolder = Config.FileTypesPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
if (command == "FileUpload"):
return self.uploadFile(resourceType, currentFolder)
# Create Url
url = combinePaths( self.webUserFilesFolder, currentFolder )
# Begin XML
s += self.createXmlHeader(command, resourceType, currentFolder, url)
# Execute the command
selector = {"GetFolders": self.getFolders,
"GetFoldersAndFiles": self.getFoldersAndFiles,
"CreateFolder": self.createFolder,
}
s += selector[command](resourceType, currentFolder)
s += self.createXmlFooter()
return s
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorConnector()
data = conn.doResponse()
for header in conn.headers:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Utility functions for the File Manager Connector for Python
"""
import string, re
import os
import config as Config
# Generic manipulation functions
def removeExtension(fileName):
index = fileName.rindex(".")
newFileName = fileName[0:index]
return newFileName
def getExtension(fileName):
index = fileName.rindex(".") + 1
fileExtension = fileName[index:]
return fileExtension
def removeFromStart(string, char):
return string.lstrip(char)
def removeFromEnd(string, char):
return string.rstrip(char)
# Path functions
def combinePaths( basePath, folder ):
return removeFromEnd( basePath, '/' ) + '/' + removeFromStart( folder, '/' )
def getFileName(filename):
" Purpose: helper function to extrapolate the filename "
for splitChar in ["/", "\\"]:
array = filename.split(splitChar)
if (len(array) > 1):
filename = array[-1]
return filename
def sanitizeFolderName( newFolderName ):
"Do a cleanup of the folder name to avoid possible problems"
# Remove . \ / | : ? * " < > and control characters
return re.sub( '\\.|\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]', '_', newFolderName )
def sanitizeFileName( newFileName ):
"Do a cleanup of the file name to avoid possible problems"
# Replace dots in the name with underscores (only one dot can be there... security issue).
if ( Config.ForceSingleExtension ): # remove dots
newFileName = re.sub ( '\\.(?![^.]*$)', '_', newFileName ) ;
newFileName = newFileName.replace('\\','/') # convert windows to unix path
newFileName = os.path.basename (newFileName) # strip directories
# Remove \ / | : ? *
return re.sub ( '\\\\|\\/|\\||\\:|\\?|\\*|"|<|>|[\x00-\x1f\x7f-\x9f]/', '_', newFileName )
def getCurrentFolder(currentFolder):
if not currentFolder:
currentFolder = '/'
# Check the current folder syntax (must begin and end with a slash).
if (currentFolder[-1] <> "/"):
currentFolder += "/"
if (currentFolder[0] <> "/"):
currentFolder = "/" + currentFolder
# Ensure the folder path has no double-slashes
while '//' in currentFolder:
currentFolder = currentFolder.replace('//','/')
# Check for invalid folder paths (..)
if '..' in currentFolder or '\\' in currentFolder:
return None
# Check for invalid folder paths (..)
if re.search( '(/\\.)|(//)|([\\\\:\\*\\?\\""\\<\\>\\|]|[\x00-\x1F]|[\x7f-\x9f])', currentFolder ):
return None
return currentFolder
def mapServerPath( environ, url):
" Emulate the asp Server.mapPath function. Given an url path return the physical directory that it corresponds to "
# This isn't correct but for the moment there's no other solution
# If this script is under a virtual directory or symlink it will detect the problem and stop
return combinePaths( getRootPath(environ), url )
def mapServerFolder(resourceTypePath, folderPath):
return combinePaths ( resourceTypePath , folderPath )
def getRootPath(environ):
"Purpose: returns the root path on the server"
# WARNING: this may not be thread safe, and doesn't work w/ VirtualServer/mod_python
# Use Config.UserFilesAbsolutePath instead
if environ.has_key('DOCUMENT_ROOT'):
return environ['DOCUMENT_ROOT']
else:
realPath = os.path.realpath( './' )
selfPath = environ['SCRIPT_FILENAME']
selfPath = selfPath [ : selfPath.rfind( '/' ) ]
selfPath = selfPath.replace( '/', os.path.sep)
position = realPath.find(selfPath)
# This can check only that this script isn't run from a virtual dir
# But it avoids the problems that arise if it isn't checked
raise realPath
if ( position < 0 or position <> len(realPath) - len(selfPath) or realPath[ : position ]==''):
raise Exception('Sorry, can\'t map "UserFilesPath" to a physical path. You must set the "UserFilesAbsolutePath" value in "editor/filemanager/connectors/py/config.py".')
return realPath[ : position ]
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python (CGI and WSGI).
"""
from time import gmtime, strftime
import string
def escape(text, replace=string.replace):
"""
Converts the special characters '<', '>', and '&'.
RFC 1866 specifies that these characters be represented
in HTML as < > and & respectively. In Python
1.5 we use the new string.replace() function for speed.
"""
text = replace(text, '&', '&') # must be done 1st
text = replace(text, '<', '<')
text = replace(text, '>', '>')
text = replace(text, '"', '"')
return text
def convertToXmlAttribute(value):
if (value is None):
value = ""
return escape(value)
class BaseHttpMixin(object):
def setHttpHeaders(self, content_type='text/xml'):
"Purpose: to prepare the headers for the xml to return"
# Prevent the browser from caching the result.
# Date in the past
self.setHeader('Expires','Mon, 26 Jul 1997 05:00:00 GMT')
# always modified
self.setHeader('Last-Modified',strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()))
# HTTP/1.1
self.setHeader('Cache-Control','no-store, no-cache, must-revalidate')
self.setHeader('Cache-Control','post-check=0, pre-check=0')
# HTTP/1.0
self.setHeader('Pragma','no-cache')
# Set the response format.
self.setHeader( 'Content-Type', content_type + '; charset=utf-8' )
return
class BaseXmlMixin(object):
def createXmlHeader(self, command, resourceType, currentFolder, url):
"Purpose: returns the xml header"
self.setHttpHeaders()
# Create the XML document header
s = """<?xml version="1.0" encoding="utf-8" ?>"""
# Create the main connector node
s += """<Connector command="%s" resourceType="%s">""" % (
command,
resourceType
)
# Add the current folder node
s += """<CurrentFolder path="%s" url="%s" />""" % (
convertToXmlAttribute(currentFolder),
convertToXmlAttribute(url),
)
return s
def createXmlFooter(self):
"Purpose: returns the xml footer"
return """</Connector>"""
def sendError(self, number, text):
"Purpose: in the event of an error, return an xml based error"
self.setHttpHeaders()
return ("""<?xml version="1.0" encoding="utf-8" ?>""" +
"""<Connector>""" +
self.sendErrorNode (number, text) +
"""</Connector>""" )
def sendErrorNode(self, number, text):
if number != 1:
return """<Error number="%s" />""" % (number)
else:
return """<Error number="%s" text="%s" />""" % (number, convertToXmlAttribute(text))
class BaseHtmlMixin(object):
def sendUploadResults( self, errorNo = 0, fileUrl = '', fileName = '', customMsg = '' ):
self.setHttpHeaders("text/html")
"This is the function that sends the results of the uploading process"
"Minified version of the document.domain automatic fix script (#1919)."
"The original script can be found at _dev/domain_fix_template.js"
return """<script type="text/javascript">
(function(){var d=document.domain;while (true){try{var A=window.parent.document.domain;break;}catch(e) {};d=d.replace(/.*?(?:\.|$)/,'');if (d.length==0) break;try{document.domain=d;}catch (e){break;}}})();
window.parent.OnUploadCompleted(%(errorNumber)s,"%(fileUrl)s","%(fileName)s","%(customMsg)s");
</script>""" % {
'errorNumber': errorNo,
'fileUrl': fileUrl.replace ('"', '\\"'),
'fileName': fileName.replace ( '"', '\\"' ) ,
'customMsg': customMsg.replace ( '"', '\\"' ),
}
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector/QuickUpload for Python (WSGI wrapper).
See config.py for configuration settings
"""
from connector import FCKeditorConnector
from upload import FCKeditorQuickUpload
import cgitb
from cStringIO import StringIO
# Running from WSGI capable server (recomended)
def App(environ, start_response):
"WSGI entry point. Run the connector"
if environ['SCRIPT_NAME'].endswith("connector.py"):
conn = FCKeditorConnector(environ)
elif environ['SCRIPT_NAME'].endswith("upload.py"):
conn = FCKeditorQuickUpload(environ)
else:
start_response ("200 Ok", [('Content-Type','text/html')])
yield "Unknown page requested: "
yield environ['SCRIPT_NAME']
return
try:
# run the connector
data = conn.doResponse()
# Start WSGI response:
start_response ("200 Ok", conn.headers)
# Send response text
yield data
except:
start_response("500 Internal Server Error",[("Content-type","text/html")])
file = StringIO()
cgitb.Hook(file = file).handle()
yield file.getvalue()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
This is the "File Uploader" for Python
"""
import os
from fckutil import *
from fckcommands import * # default command's implementation
from fckconnector import FCKeditorConnectorBase # import base connector
import config as Config
class FCKeditorQuickUpload( FCKeditorConnectorBase,
UploadFileCommandMixin,
BaseHttpMixin, BaseHtmlMixin):
def doResponse(self):
"Main function. Process the request, set headers and return a string as response."
# Check if this connector is disabled
if not(Config.Enabled):
return self.sendUploadResults(1, "This file uploader is disabled. Please check the \"editor/filemanager/connectors/py/config.py\"")
command = 'QuickUpload'
# The file type (from the QueryString, by default 'File').
resourceType = self.request.get('Type','File')
currentFolder = "/"
# Check for invalid paths
if currentFolder is None:
return self.sendUploadResults(102, '', '', "")
# Check if it is an allowed command
if ( not command in Config.ConfigAllowedCommands ):
return self.sendUploadResults( 1, '', '', 'The %s command isn\'t allowed' % command )
if ( not resourceType in Config.ConfigAllowedTypes ):
return self.sendUploadResults( 1, '', '', 'Invalid type specified' )
# Setup paths
self.userFilesFolder = Config.QuickUploadAbsolutePath[resourceType]
self.webUserFilesFolder = Config.QuickUploadPath[resourceType]
if not self.userFilesFolder: # no absolute path given (dangerous...)
self.userFilesFolder = mapServerPath(self.environ,
self.webUserFilesFolder)
# Ensure that the directory exists.
if not os.path.exists(self.userFilesFolder):
try:
self.createServerFoldercreateServerFolder( self.userFilesFolder )
except:
return self.sendError(1, "This connector couldn\'t access to local user\'s files directories. Please check the UserFilesAbsolutePath in \"editor/filemanager/connectors/py/config.py\" and try again. ")
# File upload doesn't have to return XML, so intercept here
return self.uploadFile(resourceType, currentFolder)
# Running from command line (plain old CGI)
if __name__ == '__main__':
try:
# Create a Connector Instance
conn = FCKeditorQuickUpload()
data = conn.doResponse()
for header in conn.headers:
if not header is None:
print '%s: %s' % header
print
print data
except:
print "Content-Type: text/plain"
print
import cgi
cgi.print_exception()
| Python |
#!/usr/bin/env python
"""
FCKeditor - The text editor for Internet - http://www.fckeditor.net
Copyright (C) 2003-2009 Frederico Caldeira Knabben
== BEGIN LICENSE ==
Licensed under the terms of any of the following licenses at your
choice:
- GNU General Public License Version 2 or later (the "GPL")
http://www.gnu.org/licenses/gpl.html
- GNU Lesser General Public License Version 2.1 or later (the "LGPL")
http://www.gnu.org/licenses/lgpl.html
- Mozilla Public License Version 1.1 or later (the "MPL")
http://www.mozilla.org/MPL/MPL-1.1.html
== END LICENSE ==
Connector for Python and Zope.
This code was not tested at all.
It just was ported from pre 2.5 release, so for further reference see
\editor\filemanager\browser\default\connectors\py\connector.py in previous
releases.
"""
from fckutil import *
from connector import *
import config as Config
class FCKeditorConnectorZope(FCKeditorConnector):
"""
Zope versiof FCKeditorConnector
"""
# Allow access (Zope)
__allow_access_to_unprotected_subobjects__ = 1
def __init__(self, context=None):
"""
Constructor
"""
FCKeditorConnector.__init__(self, environ=None) # call superclass constructor
# Instance Attributes
self.context = context
self.request = FCKeditorRequest(context)
def getZopeRootContext(self):
if self.zopeRootContext is None:
self.zopeRootContext = self.context.getPhysicalRoot()
return self.zopeRootContext
def getZopeUploadContext(self):
if self.zopeUploadContext is None:
folderNames = self.userFilesFolder.split("/")
c = self.getZopeRootContext()
for folderName in folderNames:
if (folderName <> ""):
c = c[folderName]
self.zopeUploadContext = c
return self.zopeUploadContext
def setHeader(self, key, value):
self.context.REQUEST.RESPONSE.setHeader(key, value)
def getFolders(self, resourceType, currentFolder):
# Open the folders node
s = ""
s += """<Folders>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["Folder"]):
s += """<Folder name="%s" />""" % (
convertToXmlAttribute(name)
)
# Close the folders node
s += """</Folders>"""
return s
def getZopeFoldersAndFiles(self, resourceType, currentFolder):
folders = self.getZopeFolders(resourceType, currentFolder)
files = self.getZopeFiles(resourceType, currentFolder)
s = folders + files
return s
def getZopeFiles(self, resourceType, currentFolder):
# Open the files node
s = ""
s += """<Files>"""
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
for (name, o) in zopeFolder.objectItems(["File","Image"]):
s += """<File name="%s" size="%s" />""" % (
convertToXmlAttribute(name),
((o.get_size() / 1024) + 1)
)
# Close the files node
s += """</Files>"""
return s
def findZopeFolder(self, resourceType, folderName):
# returns the context of the resource / folder
zopeFolder = self.getZopeUploadContext()
folderName = self.removeFromStart(folderName, "/")
folderName = self.removeFromEnd(folderName, "/")
if (resourceType <> ""):
try:
zopeFolder = zopeFolder[resourceType]
except:
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=resourceType, title=resourceType)
zopeFolder = zopeFolder[resourceType]
if (folderName <> ""):
folderNames = folderName.split("/")
for folderName in folderNames:
zopeFolder = zopeFolder[folderName]
return zopeFolder
def createFolder(self, resourceType, currentFolder):
# Find out where we are
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
errorNo = 0
errorMsg = ""
if self.request.has_key("NewFolderName"):
newFolder = self.request.get("NewFolderName", None)
zopeFolder.manage_addProduct["OFSP"].manage_addFolder(id=newFolder, title=newFolder)
else:
errorNo = 102
return self.sendErrorNode ( errorNo, errorMsg )
def uploadFile(self, resourceType, currentFolder, count=None):
zopeFolder = self.findZopeFolder(resourceType, currentFolder)
file = self.request.get("NewFile", None)
fileName = self.getFileName(file.filename)
fileNameOnly = self.removeExtension(fileName)
fileExtension = self.getExtension(fileName).lower()
if (count):
nid = "%s.%s.%s" % (fileNameOnly, count, fileExtension)
else:
nid = fileName
title = nid
try:
zopeFolder.manage_addProduct['OFSP'].manage_addFile(
id=nid,
title=title,
file=file.read()
)
except:
if (count):
count += 1
else:
count = 1
return self.zopeFileUpload(resourceType, currentFolder, count)
return self.sendUploadResults( 0 )
class FCKeditorRequest(object):
"A wrapper around the request object"
def __init__(self, context=None):
r = context.REQUEST
self.request = r
def has_key(self, key):
return self.request.has_key(key)
def get(self, key, default=None):
return self.request.get(key, default)
"""
Running from zope, you will need to modify this connector.
If you have uploaded the FCKeditor into Zope (like me), you need to
move this connector out of Zope, and replace the "connector" with an
alias as below. The key to it is to pass the Zope context in, as
we then have a like to the Zope context.
## Script (Python) "connector.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=*args, **kws
##title=ALIAS
##
import Products.zope as connector
return connector.FCKeditorConnectorZope(context=context).doResponse()
"""
| Python |
"""
========================================================================
FILE: ensemble_field_function.py
LAST MODIFIED: 23 September 2009
DESCRIPTION:
Classes for combining information and functions of mesh topology
(topology.mesh.mesh_ensemble, element.element_types), basis
(basis.basis), and mapping (mapper.mapper)
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
import scipy
from basis import basis
from topology import mesh
from topology import element_types
import mapper
import copy
class ensemble_field_function:
""" Class that combines basis, mesh and mapper to create a field.
Acts as a wrapper for methods in mesh and mapper and handles field
evaluation.
"""
def __init__( self, name, dimensions, debug = 0 ):
self.name = name # string
self.dimensions = dimensions # integer
self.basis = None # basis object
self.basis_type = None # string
self.mesh = None # mesh_ensemble object
self.mapper = mapper.mapper() # parameter mapper object
self.parameters = None
self.subfields = {} # {subfield number: subfield}
self.submesh_map = {} # {submesh: corresponding subfield}
self.subfield_counter = 0
self.is_element = False
self.debug = debug
#==================================================================#
def set_basis( self, types ):
""" Instantiate a basis object of defined type. types is either a
string or list of strings for multiple basis functions. If a
string, assume same basis type for all dimensions.
"""
if not isinstance( types, list ):
types = [ types ] * self.dimensions
if len( types ) != self.dimensions:
print 'ERROR: set_basis: incorrect number of basis types, need', self.dimensions
return
else:
self.basis = basis.make_basis( self.dimensions, types )
if self.basis:
self.basis_type = self.basis.type
return 1
else:
return
#==================================================================#
def set_new_mesh( self, name ):
""" Instantiate a new mesh_ensemble object.
"""
self.mesh = mesh.mesh_ensemble( name, self.dimensions )
if self.mesh:
return 1
else:
return
#==================================================================#
def set_mesh( self, mesh ):
""" Set an existing mesh object to be the field topology
automatically updates global_map.
"""
self.mesh = mesh
self.map_parameters()
return 1
#==================================================================#
def add_element( self, element ):
""" Add an existing element (element or ensemble field function
object) to the mesh. returns new element number for convenience.
"""
if element.is_element:
n = self.mesh.add_element( element )
if n == None:
print 'ERROR: ensemble_field_function.add_element: unable to add element to mesh'
return
else:
n = self._add_subfield( element )
if n == None:
print 'ERROR: ensemble_field_function.add_element: unable to add subfield to mesh'
return
return n
#==================================================================#
def create_elements( self, type, number_of_elements ):
""" Create new elements of the specified type and add to mesh.
Returns a tuple of new element numbers for convenience.
"""
n_all = []
for i in range( number_of_elements ):
# create element
element = element_types.create_element( type )
if element:
n = self.mesh.add_element( element )
if n == None:
print 'ERROR: ensemble_field_function.create_element: unable to add element to mesh'
return
n_all.append(n)
else:
print 'ERROR ensemble_field_function.create_element: unable to create element'
return
return tuple(n_all)
#==================================================================#
def _add_subfield( self, subfield ):
""" Add an existing ensemble field function object as a subfield
update self.mesh connectivity.
"""
self.submesh_map[ subfield.mesh ] = subfield
self.subfields[self.subfield_counter] = subfield
n = self.mesh.add_element( subfield.mesh )
self.subfield_counter += 1
return n
#==================================================================#
def remove_element( self, element_number ):
""" Remove element element_number from the mesh.
"""
if self.mesh.remove_element( element_number ):
# removed element from the mapper
if self.mapper.remove_element( element_number ):
return 1
return
#==================================================================#
def connect_element_points( self, points ):
""" Wrapper for mesh_ensemble's connect method.
"""
if self.mesh.connect( points ):
return 1
else:
return
#==================================================================#s
def connect_to_hanging_point( self, host_element, element_coordinates, connected_points ):
""" Wrapper for mesh_ensemble's connect_to_hanging_point method.
"""
if self.mesh.connect_to_hanging_point( host_element, element_coordinates, connected_points ):
return 1
else:
return
#==================================================================#
def map_parameters( self ):
""" Use mapper object to generates global node and elements
numbers using connectivity information.
"""
self.mapper.set_parent_field( self )
if self.mapper.do_mapping():
return 1
else:
print 'ERROR: ensemble_field_function.map_parameters failed'
return
#==================================================================#
def get_mapping( self ):
""" Returns the mapping dictionaries generated by the mapper.
"""
en_to_el = copy.deepcopy( self.mapper._ensemble_to_element_map )
el_to_en = copy.deepcopy( self.mapper._element_to_ensemble_map )
return ( en_to_el, el_to_en )
#==================================================================#
def get_number_of_ensemble_points( self ):
""" Returns the number of ensemble points in the field by
querying the mapper.
"""
return self.mapper.get_number_of_ensemble_points()
#==================================================================#
def set_parameters( self, parameters ):
""" Set the parameters for the field. Not sure if this is
necessary
"""
# check parameter length
if len( parameters ) != self.mapper.get_number_of_ensemble_points():
print 'ERROR: ensemble_field_function:set_parameters: wrong number of parameter sets, there are', self.mapper.get_number_of_ensemble_points(), 'nodes'
return
else:
self.parameters = parameters
return 1
#==================================================================#
def evaluate_field_at_element_node( self, element, point ):
# gets the values at element int:element point int:point
# by querying mapper
element_parameters = self.mapper.get_element_parameters( element, self.parameters )
if element_parameters == None:
print 'ERROR: ensemble_field_function.evaluate_field_at_element_point: unable to get element parameters from mapper'
return None
else:
try:
point_values = element_parameters[point]
except IndexError:
print 'ERROR: ensemble_field_function.evaluate_field_at_element_point: invalid point in element'
return None
else:
return point_values[0]
#==================================================================#
def evaluate_field_in_mesh( self, density, parameters = None ):
""" Evaluates the field over the whole mesh, i.e. in all
elements. Returns a list of field values.
density is the sampling density per dimension in each element.
parameters is a list of field parameters, with a list for each
ensemble point. If parameters is not passed, will look to see if
parameters have been set. If not, returns error.
"""
if parameters == None:
parameters = self.parameters
# check that there are parameters
if parameters == None:
print 'ERROR: ensemble_field_function.evaluate_field_in_mesh: no parameters passed or set'
return
# check for right number of density values
if isinstance( density, int ):
density = [density] * self.dimensions
elif len( density ) != self.dimensions:
print 'ERROR: evaluate_element: needed', self.dimensions, 'density values. Got', len( density )
return
field_values = []
element_field_values = None
for element_number in self.mesh.elements.keys():
# get element
element = self.mesh.elements[ element_number ]
# for each element, get element_parameters
element_parameters = self.mapper.get_element_parameters( element_number, parameters )
if element.is_element:
# if element is local, evaluate using evaluate_field_in_element
element_field_values = self._evaluate_element( element, element_parameters, density )
else:
# else element is a sub mesh, evaluate the corresponding subfield
element_field_values = self.submesh_map[ element ].evaluate_field_in_mesh( density, element_parameters )
# store evaluated values
if not element_field_values:
print 'WARNING: ensemble_field_function.evaluate_field_in_mesh: evaluation failed in element', element_number
else:
field_values += element_field_values
return field_values
#==================================================================#
#~ def evaluate_field_in_element( self, element_number, density ):
#~ # evaluates the field in an element defined by element_number
#~
#~ # check for right number of density values
#~ if isinstance( density, int ):
#~ density = [density] * self.dimensions
#~ elif len( density ) != self.dimensions:
#~ print 'ERROR: evaluate_element: needed', self.dimensions, 'density values. Got', len( density )
#~ return 0
#~
#==================================================================#
def _evaluate_element( self, element, element_parameters, density ):
""" Evaluates a given element with its parameters.
element is an element object
element_parameters is a list parameters containing a list for
each element node.
density is a list of number of points evaluated in each element direction
"""
# check for right number of density values
if isinstance( density, int ):
density = [density] * self.dimensions
elif len( density ) != self.dimensions:
print 'ERROR: evaluate_element: needed', self.dimensions, 'density values. Got', len( density )
return None
# initialise
eval_coords = []
bases = []
eval_values = []
#~ element = self.mesh.elements[element_number]
#~ element_parameters = self._get_element_parameters( element_number )
if self.debug:
print 'element_parameters:', element_parameters
# generate evaluation points
for i in range( self.dimensions ):
eval_coords.append( scipy.linspace( element.interior[i][0], element.interior[i][1], density[i] ) )
# evaluate basis functions at each evaluation point
if self.dimensions == 1:
for i in eval_coords[0]:
if element.is_interior( [i] ):
bases.append( self.basis.eval( [i] ) )
elif self.dimensions == 2:
for i in eval_coords[0]:
for j in eval_coords[1]:
if element.is_interior( [i,j] ):
bases.append( self.basis.eval( [i,j] ) )
elif self.dimensions == 3:
for i in eval_coords[0]:
for j in eval_coords[1]:
for k in eval_coords[2]:
if element.is_interior( [i,j,k] ):
bases.append( self.basis.eval( [i,j,k] ) )
else:
print 'ERROR: ensemble_field_function.evaluate_element: unsupported dimensions'
return None
if self.debug:
print '1st basis', bases[0]
# inner product each set of basis values with element parameters
for basis in bases:
eval_values.append( scipy.dot( basis, element_parameters ) )
return eval_values
#==================================================================#
def get_element_point_evaluator( self, element_number ):
""" returns an object for evaluating points within element
element_number
"""
# check for valid element_number
try:
element = self.mesh.elements[ element_number ]
except KeyError:
print 'ERROR ensemble_field_function.get_element_point_evaluator: invalid element'
return None
else:
# if element is an element....
if element.is_element:
# get element parameters
parameters = self.mapper.get_element_parameters( element_number )
# create evaluation object
evaluator = element_point_evaluator( element, parameters, self.basis )
# else element is a subfield
else:
#~ evaluator = self.submesh_map[ element ].get_element_point_evaluator( element_number )
print 'ERROR: ensemble_field_function.get_element_point_evaluator: element', element_number, 'is a subfield'
return None
return evaluator
#==================================================================#
#~ def evaluate_field_at_element_point( self, element_number, element_coordinates, element_parameters ):
#~ # element_number is an integer
#~ # element_coordinates should be a list or tuple of xi values
#~ # e.g. [xi1, xi2]
#~ # element_parameters should be a list of parameters for each
#~ # element point
#~ # e.g. [ [p1 parameters], [p2 parameters]...]
#~
#~ element = self.mesh.elements[ element_number ]
#~
#~
#~
#~ # check coordinates are in element domain
#~
#~ if element.is_interior( element_coordinates ):
#~
#~ u_vector = []
#~
#~ if ( self.basis_type == 'cubic_hermite' ) and self.dimensions == 2:
#~ # special mapping of element parameters to the tensor product
#~ # of basis functions for 2D cubic hermite
#~ # should be improved!
#~ # goes [1 2 5 6 3 4 7 8 9 10 13 14 11 12 15 16]
#~ u_vector = []
#~ for i in range( 0, self.dimensions+1, 2 ):
#~ for j in range( 0, self.dimensions+1, 2 ):
#~ u_vector += list( element_point_values[i:i+self.dimensions, j:j+self.dimensions].ravel() )
#~
#~ else:
#~ u_vector = element_point_values.ravel()
#~
#~ if self.debug:
#~ print 'element_point_values:', element_point_values
#~ print 'u_vector:', u_vector
#~
#~ #
#~ for i in range( len( element_coordinates ) ):
#~ # evaluate basis function at element_coordinates
#~ phi = self.basis.eval( element_coordinates[i] )
#~
#~ if self.debug:
#~ print 'phi:', phi
#~
#~ if not isinstance( phi, int ):
#~ # inner-product with basis
#~ field_value = scipy.dot( phi, u_vector )
#~ if self.debug:
#~ print 'field_values:', field_values
#~ else:
#~ print 'ERROR: basis.eval'
#~ return 0
#~
#~ field_values.append( field_value )
#~
#~
#~ return field_values
#==================================================================#
class element_point_evaluator:
""" Class for objects evaluating the field within an element
"""
def __init__( self, element, parameters, basis_function ):
self.element = element
self.parameters = parameters
self.dimensions = self.element.dimensions
self.basis = basis_function
def evaluate_at_element_point( element_coordinates ):
""" Evaluates the objects element at the given element
coordinates. element_coordinates is a list.
"""
# evaluate basis function
basis_coeff = self.basis.eval( element_coordinates )
if basis_coeff != None:
try:
field_value = scipy.dot( basis_coeff, self.parameters )
return field_value
except ValueError:
print 'ERROR: element_point_evaluator.evaluate_at_element_point: dot product failed, basis_coeff and parameters misaligned'
return None
else:
print 'ERROR: element_point_evaluator.evaluate_at_element_point: unable to evaluate basis function at element coordinates:', element_coordinates
return None
| Python |
"""
========================================================================
FILE: element_types.py
LAST MODIFIED: 26 August 2009
DESCRIPTION:
Different types of elements and a constructor function to return
specified types of elements
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
#!/usr/bin/env python
#======================================================================#
# element classes
# dimension: dimension of the element
# interior: tuple of tuples of the range of value define in the interior
# of the elements for each dimension
class Element:
""" Universal element class
dimension: dimension of the element
interior: tuple of tuples of the range of value define in the interior
of the elements for each dimension
number_of_points: need to be removed. This should be inferred from
the field basis?
"""
def __init__( self, dimensions, interior, number_of_points, type ):
self.dimensions = dimensions # int
self.interior = interior # ( (xi1.min, xi1.max), (xi2.min, xi2.max), ...)
self.type = type # string
self.number_of_points = number_of_points # int
self.is_element = True
return
def get_number_of_ensemble_points( self ):
return self.number_of_points
class quad( Element ):
""" quadralateral elements
"""
def is_interior( self, coords ):
if len( coords ) != self.dimensions:
print 'ERROR: quad.is_interior: wrong number of input coordinates. Need', self.dimensions, ', got', len( coords )
return 0
for i in range( self.dimensions ):
if not (( coords[i] > self.interior[i][0] ) and ( coords[i] < self.interior[i][1] )):
return 0
return 1
class tri( Element ):
""" simplex elements
"""
def is_interior( self, coords ):
if len( coords ) != self.dimensions:
print 'ERROR: quad.is_interior: wrong number of input coordinates. Need', self.dimensions, ', got', len( coords )
return 0
else:
return sum( coords ) <= 1.0
def is_boundary( self, coords ):
if len( coords ) != self.dimensions:
print 'ERROR: quad.is_interior: wrong number of input coordinates. Need', self.dimensions, ', got', len( coords )
return 0
else:
return sum( coords ) == 1.0
#======================================================================#
def create_element( type ):
""" Contructor function to return an element of the required type
with the appropriate number and type of points.
"""
element_types = ( 'line2l', 'line2h', 'line3', \
'tri3l', 'tri3h', 'tri6',\
'quad22l', 'quad22h', 'quad23l', 'quad23h',\
'quad32l', 'quad32h', 'quad33' )
if type == element_types[0]:
# linear line
element = quad( 1, ((0,1)), 2, element_types[0])
element.add_points( 2, 1 )
elif type == element_types[1]:
# cubic hermite line
element = quad( 1, ((0,1)), 2, element_types[1])
element.add_points( 2, 2 )
elif type == element_types[2]:
# quadratic line
element = quad( 1, ((0,1)), 3, element_types[2])
element.add_points( 3, 1 )
elif type == element_types[3]:
# linear triangle
element = tri( 2, ((0,1),(0,1)), 3, element_types[3] )
elif type == element_types[4]:
# cubic hermite triangle
print 'Not implemented'
elif type == element_types[5]:
# quadratic triangle
element = tri( 2, ((0,1),(0,1)), 6, element_types[5] )
elif type == element_types[6]:
# linear quad
element = quad( 2, ((0,1),(0,1)), 4, element_types[6])
elif type == element_types[7]:
# cubic hermite quad
element = quad( 2, ((0,1),(0,1)), 4, element_types[6])
elif type == element_types[8]:
# linear quadratic quad
print 'Not implemented'
elif type == element_types[9]:
# cubic hermite quadratic quad
print 'Not implemented'
elif type == element_types[10]:
# quadratic linear quad
print 'Not implemented'
elif type == element_types[11]:
# quadratic cubic hermite quad
print 'Not implemented'
elif type == element_types[12]:
# quadratic quad
element = quad( 2, ((0,1),(0,1)), 9, element_types[6])
else:
print "ERROR: unrecognised element type"
return None
return element
#======================================================================#
| Python |
"""
========================================================================
FILE: mesh.py
LAST MODIFIED: 22 September 2009
DESCRIPTION:
class for holding information about the mesh topology
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
import element_types
class mesh_ensemble:
""" Class for holding information about field topology
"""
def __init__( self, name, dimensions, debug = 0 ):
self.name = name
self.dimensions = dimensions # number of dimensions of the mesh topology
self.element_counter = 0 # counter of number of elements
self.hanging_point_counter = 0 # counter for number of hanging points
self.number_of_points = None # number of unique ensemble points
self.elements = {} # { element_number: element, element_number: sub mesh_ensemble }
self.connectivity = {} # { ( element_num, point_num, ?? ) : [(element_num, point_num, ??), ...]] } !! needs to incorporate topological information: xi orientation and element CS density
self.hanging_points = {} # { hanging_point number: hanging_point, ... }
self.element_points = {} # { element_number: [ element_points ] } maps element to its element points
self.is_element = False
self.debug = debug
#==================================================================#
def add_element( self, element ):
""" adds an element to the mesh. Element can either be an element
object or another mesh_ensemble. Element is added to the elements
dict as a value with an element number. get_number_of_points is called
to get the number of entries to add to connectivity and the
element_points map.
returns element number for convenience.
"""
self.elements[ self.element_counter ] = element
self.element_points[self.element_counter] = []
for p in range( 0, element.get_number_of_ensemble_points() ):
self.connectivity.update( { ( self.element_counter, p ): []} )
self.element_points[ self.element_counter ].append( ( self.element_counter, p ) )
self.element_counter += 1
return (self.element_counter - 1)
#==================================================================#
def remove_element( self, element_number ):
""" removes element element_number from the elements dict, and all
entries the element from connectivity. Decreases element
counter by 1.
"""
# check for valid element number
if element_number not in self.elements.keys():
print 'ERROR: topology.remove_element: element', element_number, 'does not exist'
return None
# removed from elements dict
del self.elements[element_number]
# removed element points from connectivity
element_points = self.element_points[ element_number ]
# for each element point
for point in element_points:
# get points its connected to
connected_points = self.connectivity[ point ]
# remove this element point for its connected points
for connected_point in connected_points:
self.connectivity[ connected_point ].remove( point )
# removed current element point entry
del self.connectivity[ point ]
# removed element points map entry
del self.element_points[ element_number ]
# decrease element counter
self.element_counter -= 1
return 1
#==================================================================#
def get_number_of_ensemble_points( self ):
""" calculates the number of unique ensemble points in the mesh
by going through the connectivity dict.
"""
gp = 0 # global points number
assigned = [] # list of element points already assigned a global number
# account for points connected to hanging nodes
#~ if self.hanging_points:
#~ for points in self.hanging_point_connectivity.values():
#~ assigned += points
# loop through each element point in the connectivity dict
element_points = self.connectivity.keys()
element_points.sort()
if self.debug:
print 'sorted element points:', element_points
for element_point in element_points:
# check if point has already been assigned a global number
if (element_point not in assigned):
# record element points assigned
assigned += [element_point] + self.connectivity[element_point]
if self.debug:
print 'assigned:', assigned
# if not a hanging point, count as an ensemble point
if element_point[0] != -1:
gp += 1
self.number_of_points = gp
return self.number_of_points
#==================================================================#
def connect( self, common_points ):
""" define how the elements are connected
common_points is a list of tuples of element nodes, or coordinates at the
same ensemble mesh position:
[ (element_num, node_num1, ??), (element_num2, (element_xi), ??), ...]
!! should incorporate information about element coord orientation and coord density here !!
!! should be able to connect to any position in an element, not only to other element points => hanging nodes handled naturally !!
!! => connectivity contains extra topology info!!
"""
for point in common_points:
if point not in self.connectivity.keys():
print 'ERROR: toplogy.connect: point', point, 'does not exist'
avail_keys = self.connectivity.keys()
avail_keys.sort()
print 'available points to connect:\n', avail_keys
return None
# append other points to its list
other_points = list( common_points[:] )
other_points.remove( point )
for other_point in other_points:
if other_point not in self.connectivity[point]:
self.connectivity[point].append( other_point )
return 1
#==================================================================#
def connect_to_hanging_point( self, host_element, element_coordinates, connected_points ):
""" host_element: int
element_coordinates: [xi2, xi2,...]
connected_points: [ (element_num, point_num), ...]
creates a hanging point in host_element at element_coordinates,
and connects connected_points to the hanging point
"""
# create hanging point
if self._add_hanging_point( host_element, element_coordinates ):
# add entry to connectivity
connected_points.append( (-1, self.hanging_point_counter - 1 ) )
# connect
self.connect( connected_points )
return 1
else:
print 'ERROR: topology.connect_to_hanging_point: failed to add hanging_point'
return None
#==================================================================#
def _add_hanging_point( self, host_element, element_coordinates):
""" adds a hanging point to the mesh in host_element at
element_coordinates
"""
# check for valid element and number of coordinates
# will have trouble with child elements with different dimensionality
if host_element in self.elements.keys():
if len( element_coordinates ) == self.elements[host_element].dimensions:
# instantiate hanging_point
hanging_point = hanging_point( host_element, element_coordinates )
# add hanging point to hanging_points dict and connectivity under element -1
self.hanging_points[self.hanging_point_counter] = hanging_point
self.connectivity[ (-1, self.hanging_point_counter) ] = []
self.hanging_point_counter += 1
return 1
else:
print 'ERROR: topology.add_hanging_point: incorrect number of element coordinates. Need', self.elements[host_element].dimensions,', got', len( element_coordinates )
return None
else:
print 'ERROR: topology.add_hanging_point: element', host_element, 'does not exist'
return None
#==================================================================#
#~ def _get_element_points( self, element_number ):
#~ # returns a list of tuples containing all elements of element
#~ # element_number
#~
#~ # check for valid element
#~ if element_number not in self.elements.keys():
#~ print 'ERROR: topology._get_element_points: element', element_number, 'does not exist'
#~ return 0
#~
#~ element_points = []
#~ ckeys = self.connectivity.keys()
#~ ckeys.sort
#~ ckeys_iter = iter(ckeys)
#~ done = 0
#~
#~ # look through sorted connectivity keys until 1st element point
#~ # of element
#~ while not done:
#~ key = ckeys_iter.next()
#~ if key[0] = element_number:
#~ element_points.append( key )
#==================================================================#
#~ def add_local_element( self, type ):
#~ """ adds a element to the mesh. Type is a string of the of the
#~ type of element. The element is appended to the
#~ self.local_elements dict with the current element_counter value.
#~ List of nodes in that element are appended to the connectivity
#~ dict. self.element_counter is increased by 1
#~ """
#~ # instantiate element
#~ element = element_types.create_element( type )
#~
#~ if element:
#~ # add to local_elements dict
#~ self.elements[ self.element_counter ] = element
#~
#~ # add nodes as keys to connectivity
#~ for p in range(0, element.number_of_points ):
#~ self.connectivity.update( { [element_counter, p]: []} )
#~
#~ element_number += 1
#~ return 1
#~ else:
#~ print 'ERROR: mesh_ensemble.add_element failed'
#~ return 0
#==================================================================#
#~ def add_sub_mesh( self, sub_mesh ):
#~ """ sub_mesh is an ensemble_mesh instance. it is given an element
#~ number and appended to the self.elements dict. Queries the sub_mesh's
#~ get_number_of_points() to get number of points exposed to the parent.
#~ """
#~
#~
#~ # add sub mesh elements/element_points to connectivity dict using
#~ # the connectivity in the sub_mesh
#~ e_start = len( self.elements ) # element number of elements in the sub mesh are padded by this number
#~
#~ sub_mesh_elements = sub_mesh.connectivity.keys()
#~ sub_mesh_elements.sort()
#~
#~ for key in sub_mesh_elements:
#~
#~ sub_element = key[0]
#~ sub_point = key [1]
#~
#~ # add new connectivity key
#~ self.connectivity.update( { ( sub_element + e_start, sub_point ): [] }
#~ # add values to new connectivity key
#~ for ( e, p ) in sub_mesh.connectivity[key]:
#~ self.connectivity[ sub_element + e_start, sub_point ].append( ( e + e_start, p ) )
#~
#~ # map element number to its sub_mesh, and sub mesh element number
#~ self.sub_mesh_element_map.update( { ( sub_element + e_start, sub_point ): (sub_mesh_number, sub_element) } )
#~
#~ return 1
# hanging point object. Stored information about its host_element and
# host element coordinates
class hanging_point:
""" Class for holding information about a hanging_point (node)
"""
def __init__(self, host_element, element_coordinates):
self.host_element = host_element
self.element_coordinates = tuple( element_coordinates )
def get_host_element( self ):
return self.host_element
def get_element_coordinates( self ):
return self.element_coordinates
| Python |
"""
========================================================================
FILE: geometric_field.py
LAST MODIFIED: 23 September 2009
DESCRIPTION:
class for a ensemble_field_function representing a mesh geometry.
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
import scipy
import template_fields
from enthought.mayavi import mlab
class geometric_field:
""" Class for an ensemble_field representing the geometry of an
object. Either instantiated with an existing ensemble_field, or if
none, a new ensemble_field will be instantiated from the
template_fields module with the given field_dimension and basis_type.
"""
def __init__(self, name, dimensions, ensemble_field_function = None, field_dimensions = None, field_basis = None ):
self.name = name
self.dimensions = dimensions
self.field_parameters = []
self.points = [] # list of point objects
self.points_to_ensemble_map = {} # { points index: ensemble_point_number }
self.ensemble_to_points_map = {} # { ensemble_point_number: points index }
self.named_points_map = {} # { point_name: points index }
self.points_counter = 0
self.ensemble_point_counter = 0
for i in range( self.dimensions ):
self.field_parameters.append( [] )
if ensemble_field_function:
# create the appropriate number of geometric points for the ensemble
# points in the mesh
self.ensemble_field_function = ensemble_field_function
self._create_ensemble_points()
else:
# instantiate a new ensemble_field_function
self.ensemble_field_function = template_fields.empty_field( self.name+'field', field_dimensions, field_basis )
#==================================================================#
def _create_ensemble_points( self ):
""" Creates a geometric point for each ensemble point in the
ensemble field function upon instantiation with an existing
ensemble_field_function
"""
# get total number of points need to make
n_points = self.ensemble_field_function.get_number_of_ensemble_points()
for i in range( n_points ):
# make geometric_point object
point = geometric_point( self.dimensions, ensemble_point_number = i )
self.points.append( point )
self.ensemble_to_points_map[i] = self.points_counter
self.points_to_ensemble_map[self.points_counter] = i
self.points_counter += 1
return 1
#==================================================================#
def get_number_of_points( self ):
""" returns total number of geometric_points in the
geometric_field
"""
return len(self.points)
#==================================================================#
def set_field_parameters( self, field_parameters ):
""" Sets the field parameters for the ensemble_field. A
geometric point is create at each location.
field_parameters should be a list with self.dimension number of
sub lists containing the parameters from each dimension
"""
# checks
if len( field_parameters ) != self.dimensions:
print 'ERROR: geometric_field.set_parameters: parameters inconsistent with number of dimensions'
return None
p_lengths = [ len(p) for p in field_parameters ]
n_ensemble_points = self.ensemble_field_function.get_number_of_ensemble_points()
if (sum(p_lengths) / self.dimensions) != p_lengths[0]:
print 'ERROR: geometric_field.set_field_parameters: parameter vector lengths not equal'
return None
if p_lengths[0] != n_ensemble_points:
print 'ERROR: geometric_field.set_field_parameters: number of given parameters (', p_lengths[0], ') does not match number of field ensemble points (', n_ensemble_points, ')'
return None
# if nothings wrong so far
#~ self.field_parameters = scipy.array( field_parameters )
self.field_parameters[:] = field_parameters[:]
# set geometric points associated with ensemble point with these parameters
for i in range( n_ensemble_points ):
fp = [ v[i] for v in self.field_parameters ]
self.points[ self.ensemble_to_points_map[i] ].set_field_parameters( fp )
return 1
#==================================================================#
def add_geometric_point( self, field_parameters, name = None ):
""" Add a point to the geometric field.
field parameters length must = field dimensions
returns new point number
"""
if len( field_parameters ) != self.dimensions:
print 'ERROR: geometric_field.add_point: parameters length/ dimension mismatch'
return
self.points.append( geometric_point( self.dimensions, field_parameters ) )
if name:
self.named_points_map[name] = self.points_counter
self.points_counter += 1
return ( self.points_counter - 1 )
#==================================================================#
def add_element( self, element, points, debug = 0 ):
""" Add an element object to the field, connecting its element
points to the geometric point numbers given.
element is an element or subfield object.
points is a list of geometric point numbers in the order of the
element points of the element being added.
"""
# check for right number of points
element_points = element.get_number_of_ensemble_points()
if element_points != len( points ):
print 'ERROR: geometric_field.add_element: number of points', len( points ), 'does not match number of element points', element_points
return
# element point counter
ep = 0
# add element to mesh
e_number = self.ensemble_field_function.add_element( element )
# connect element and update mapper
for p in points:
# if point is an existing ensemble point
if p in self.points_to_ensemble_map.keys():
ensemble_point = self.points_to_ensemble_map[p]
# get element point tuple for current connection point
connected_eps = self.ensemble_field_function.mapper.get_ensemble_point_element_points( ensemble_point )
if debug:
print 'connecting', (e_number, ep), 'to:', connected_eps
# connect
connected_eps.append( ( e_number, ep ) )
self.ensemble_field_function.connect_element_points( connected_eps )
else:
# otherwise point maps to a new ensemble point
#~ new_ensemble_point = max( self.ensemble_to_points_map.keys() ) + 1
self.points_to_ensemble_map[p] = self.ensemble_point_counter
self.ensemble_to_points_map[ self.ensemble_point_counter ] = p
self.ensemble_point_counter += 1
# add new field parameters to field_parameters
fp = self.points[p].get_field_parameters()
for i in range( self.dimensions ):
self.field_parameters[i].append( fp[i] )
ep += 1
# update mapper
self.ensemble_field_function.map_parameters()
return 1
#==================================================================#
def add_element_with_parameters( self, element, parameters ):
""" Add an element to the ensemble_field with predefined parameters
new geometric points will be created for new unique parameter
coordinates. Non-uniques will be mapped to existing ensemble
points.
parameters should be [ [d0], [d1], [d2] ]
[d0] = [ [p0], [p1], [p2] ] where [p0] is a list of the
parameters are point 0
"""
# check parameters for right dimensionality and number of points
element_points = element.get_number_of_ensemble_points()
if scipy.array(parameters).shape[0:2] != ( self.dimensions, element_points ):
print 'ERROR: geometric_field.add_element_with_parameters: parameters length/ dimension mismatch. need:', ( self.dimensions, element_points )
return None
# get geometric point numbers for connecting the element to
existing_positions = self.get_all_point_positions()
connect_points = []
for i in range( element_points ):
# ith parameter coordinates
coord = [ p[i][0] for p in parameters ]
try:
connect_points.append( existing_positions.index( coord ) )
except ValueError:
# create new geometric point at current parameter
# coordinates, and record new geometric point number
# for connection
connect_points.append( self.add_geometric_point( [ p[i] for p in parameters ] ) )
# add element
self.add_element( element, connect_points )
return 1
#==================================================================#
#~ def interactive_add_element( self, element, debug = 0):
#~ # add an existing element object to the geometric field using an
#~ # interactive mayavi interface
#~
#~ # get number of points needed
#~ element_points = element.get_number_of_ensemble_points()
#~
#~ # generate the scene in which the point picker will operate
#~ field_eval_density = 10
#~ f = mlab.figure(1)
#~ self._plot_points( label = True )
#~ self._plot_field( field_eval_density )
#~ mlab.show
#~
#~ # get the points to which the element will connect to using the
#~ # mayavi interactive points picker
#~
#==================================================================#
def get_all_point_positions( self ):
""" Returns a list containing a self.dimensions long list of
coordinates for each geometric point
"""
positions = []
for i in range( self.get_number_of_points() ):
positions.append( self.get_point_position( i ) )
return positions
#==================================================================#
def get_point_position( self, point ):
""" Returns the coordinates of a point
"""
position = []
try:
parameters = self.points[point].get_field_parameters()
except IndexError:
print 'ERROR: geometric_field.get_point_position: invalid point number'
return None
else:
for i in range(self.dimensions):
position.append( parameters[i][0] )
return position
#==================================================================#
def evaluate_geometric_field( self, density ):
""" evaluates the field for all parameter components.
Returns a list of self.dimension lists
"""
evaluation = []
# evaluate each coordinate in field
for d in self.field_parameters:
evaluation.append( scipy.array(self.ensemble_field_function.evaluate_field_in_mesh( density, d )).flatten() )
return evaluation
#==================================================================#
def display_geometric_field( self, field_eval_density, point_glyph = 'sphere', point_label = None, field_glyph = 'point', field_scale = 1.0 ):
""" Plots all geometric points and point evaluated over the field
in a mayavi scene.
"""
f = mlab.figure()
mlab.clf()
self._plot_points( point_glyph, label = point_label )
self._plot_field( field_eval_density, field_glyph, field_scale )
mlab.show()
return 1
#==================================================================#
def _plot_points( self, glyph = 'sphere', label = None ):
""" uses mayavi points3d to show the positions of all points
(with labels if label is true)
label can be 'all', or 'landmarks'
"""
# get point positions
p = scipy.array( self.get_all_point_positions() )
if self.dimensions == 3:
#~ f = mlab.figure()
points_plot = mlab.points3d( p[:,0], p[:,1], p[:,2], mode = 'sphere', scale_factor = 2.0, color = (1,0,0) )
# label all ensemble points with their index number
if label == 'all':
labels = range( len( self.points ) )
for i in range( len(labels ) ):
l = mlab.text( p[0,i], p[1,i], str(labels[i]), z = p[2,i], line_width = 0.01, width = 0.005*len(str(labels[i]))**1.1 )
elif label == 'landmarks':
m = self.named_points_map
labels = m.keys()
for label in labels:
l = mlab.text( p[m[label]][0], p[m[label]][1], label, z = p[m[label]][2], line_width = 0.01, width = 0.005*len( label )**1.1 )
return points_plot
#==================================================================#
def _plot_field( self, density, glyph = 'point', scale_factor = 1.0 ):
""" uses mayavi points3d to show the evaluated field
"""
evaluation = []
# evaluate each coordinate in field
for d in self.field_parameters:
evaluation.append( scipy.array(self.ensemble_field_function.evaluate_field_in_mesh( density, d )).flatten() )
if self.dimensions == 3:
field_plot = mlab.points3d( evaluation[0],evaluation[1],evaluation[2], mode = glyph, scale_factor = 0.8, color = (0.0,0.5,1.0))
return field_plot
#======================================================================#
class geometric_point:
""" Class of point objects used by geometric_field
"""
def __init__( self, dimensions, field_parameters = None, ensemble_point_number = None ):
self.field_parameters = None
self.ensemble_point_number = None
self.dimensions = dimensions
if field_parameters:
if len(field_parameters) != dimensions:
raise ValueError( 'ERROR: geometric_point.__init__: dimension and number of coordinates mismatch' )
return
else:
self.field_parameters = tuple( field_parameters )
if ensemble_point_number:
self.ensemble_point_number = ensemble_point_number
return
#==================================================================#
def get_dimensions( self ):
return self.dimensions
#==================================================================#
def set_field_parameters( self, field_parameters ):
if len(field_parameters) != self.dimensions:
raise ValueError( 'ERROR: geometric_point.set_field_parameters: dimension and number of coordinates mismatch' )
return
self.field_parameters = list( field_parameters )
return 1
#==================================================================#
def get_field_parameters( self ):
return self.field_parameters
#==================================================================#
def set_ensemble_point_number( self, n ):
self.ensemble_point_number = n
#==================================================================#
def get_ensemble_point_number( self ):
return self.ensemble_point_number
#=Fitting related======================================================#
#~ class geometric_field_fitter:
#~ def __init__( self, geometric_field ):
#~
#~ self.geo_field = geometric_field
#~ self.dimensions = self.geo_field.dimensions
#~
#~ def _get_element_map( self ):
#~ # creates a mapping of all real elements to ensemble points
#~
#~ def _get_element_evaluators( self ):
#~ # get element point evaluators for each element
#~
#~ def set_data( self, data ):
#~ # data should be a list with self.dimension number of sub lists
#~ # or arrays containing the coordinates of datapoints
#~ # all sublists must have same length
#~
#~ if len( data ) != self.dimensions:
#~ print 'ERROR: geometric_field.set_data: data inconsistent with number of dimensions'
#~ return None
#~
#~ lengths = [ len(d) for d in data ]
#~ if (sum(lengths) / self.dimensions) != lengths[0]:
#~ print 'ERROR: geometric_field.set_data: data vector lengths not equal'
#~ return None
#~
#~ self.fitting_data = data
#~
#~ return 1
#~
#~ def fit( self, iterations, search_elements ):
#~ # iterations: number of fitting iterations
#~ # search_elements: number of closest elements to perform closes distance search for each datapoint
#~
#~ # assign data points to elements
#~ self.allocate_element()
#~
#~ # calculate initial error
#~ self.calculate_error()
#~
| Python |
"""
========================================================================
FILE: template_fields.py
LAST MODIFIED: 01 September 2009
DESCRIPTION:
functions to instantiate ensemble_field_functions with common quadratic
triangular mesh topologies.
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
#!/usr/bin/env python
import ensemble_field_function as E
import scipy
#=============#
# empty field #
#=============#
def empty_field( name, dimensions, basis_type ):
""" empty dimensions-D field with empty mesh and basis of type
basis_type
"""
f = E.ensemble_field_function( name, dimensions, debug = 0)
f.set_basis( basis_type )
f.set_new_mesh( name + '_mesh' )
return f
#===================#
# 4 -triangle patch #
#===================#
# 14
# /\
# 12 13
# 9/_10_\11
# /\ /\
# 5 6 7 8
# /____\/____\
# 0 1 2 3 4
def four_tri_patch():
dimensions = 2
elements = 4
element_type = 'tri6'
basis_type = 'triangular_quadratic_2d'
f = E.ensemble_field_function('4_tri_patch', dimensions, debug = 0)
f.set_basis( basis_type )
f.set_new_mesh('4_tri_patch')
f.create_elements(element_type, elements)
# connect elements
f.connect_element_points( [(0,2),(1,0),(2,0)] )
f.connect_element_points( [(0,4),(1,4),(3,0)] )
f.connect_element_points( [(1,2),(2,4),(3,2)] )
f.connect_element_points( [(0,3),(1,5)] )
f.connect_element_points( [(1,1),(2,5)] )
f.connect_element_points( [(1,3),(3,1)] )
f.map_parameters()
f.mapper.set_custom_ensemble_ordering( { 0:0, 1:1, 2:2, 3:6, 4:9, 5:5 ,6:7 ,7:11, 8:10,\
9:3, 10:4, 11:8, 12:13, 13:14, 14:12 } )
return f
#==================#
# 2 -triangle quad #
#==================#
# 6 _7_ 8 ______
# |\ | or /\ /
# 3| 4 |5 / \ /
# |__\| /____\/
# 0 1 2
def two_quad_patch():
dimensions = 2
elements = 2
element_type = 'tri6'
basis_type = 'triangular_quadratic_2d'
f = E.ensemble_field_function('2_quad_patch', dimensions, debug = 0)
f.set_basis( basis_type )
f.set_new_mesh('2_quad_patch')
f.create_elements(element_type, elements)
# connect elements
f.connect_element_points( [(0,2),(1,0)] )
f.connect_element_points( [(0,3),(1,5)] )
f.connect_element_points( [(0,4),(1,4)] )
#~ f.connect_element_points( [(0,2),(1,2)] )
#~ f.connect_element_points( [(0,3),(1,3)] )
#~ f.connect_element_points( [(0,4),(1,4)] )
f.map_parameters()
f.mapper.set_custom_ensemble_ordering({ 0:0, 1:1, 2:2, 3:4, 4:6, 5:3, 6:5, 7:8, 8:7 })
#~ f.mapper.set_custom_ensemble_ordering({ 0:0, 1:1, 2:2, 3:4, 4:6, 5:3, 6:8, 7:5, 8:7 })
return f
#==================#
# 3 -triangle quad #
#==================#
# 9__10__11
# /\ /\
# 5 6 7 8
# /____\/____\
# 0 1 2 3 4
def three_quad_patch():
dimensions = 2
elements = 3
element_type = 'tri6'
basis_type = 'triangular_quadratic_2d'
f = E.ensemble_field_function('3_quad_patch', dimensions, debug = 0)
f.set_basis( basis_type )
f.set_new_mesh('3_quad_patch')
f.create_elements(element_type, elements)
# connect elements
f.connect_element_points( [(0,2),(1,0),(2,0)] )
f.connect_element_points( [(0,3),(1,5)] )
f.connect_element_points( [(0,4),(1,4)] )
f.connect_element_points( [(1,1),(2,5)] )
f.connect_element_points( [(1,2),(2,4)] )
f.map_parameters()
f.mapper.set_custom_ensemble_ordering({ 0:0, 1:1, 2:2, 3:6, 4:9, 5:5,\
6:7, 7:11, 8:10,\
9:3, 10:4, 11:8 })
return f
#==========================#
# ring of 3-triangle quads #
#==========================#
# 28____29___30____31___32____33____34___35____ 28
# |\ /|\ /|\ /|\ /|
# | \ / | \ / | \ / | \ / |
# 16| 17 18 19 20 21 22 23 24 25 26 27 |16
# | \ / | \ / | \ / | \ / |
# |____\/____|____\/____|____\/____|____\/____|
# 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 0
def three_quad_ring( number_of_quads, height, radius ):
"""
number_of_quads defines the number of 2-triangle quads in the ring
( number of triangles / 2 )
height and radius determine the x,y,z parameters returned
with the ensemble_field object. z is height
"""
dimensions = 2
elements = number_of_quads
basis_type = 'triangular_quadratic_2d'
npoints = elements*6
# initialise main field ensemble
ring = E.ensemble_field_function('3_quad_ring', dimensions, debug = 0)
ring.set_basis( basis_type )
ring.set_new_mesh('3_quad_ring')
# create 3 triangle quads for the ring and add to main field ensemble
for i in range( elements ):
ring.add_element( three_quad_patch() )
# connect up quads
for i in range( elements-1 ):
ring.connect_element_points( [(i,4), (i+1,0)] )
ring.connect_element_points( [(i,8), (i+1,5)] )
ring.connect_element_points( [(i,11), (i+1,9)] )
# join end of strip to start
ring.connect_element_points( [(i+1,4), (0,0)] )
ring.connect_element_points( [(i+1,8), (0,5)] )
ring.connect_element_points( [(i+1,11), (0,9)] )
ring.map_parameters()
#==================================================================#
# remap ensemble point numbering so that node numbering increase first
# up each column of nodes
remap = {}
e = 0
old = 0
new_t1 = 0
new_t2 = elements * 4
new_t3 = elements * 7
for e in range( 0, elements ):
if e == 0:
for old in range( old, old + 5 ):
remap[old] = new_t1
new_t1 += 1
for old in range( old + 1, old + 5 ):
remap[old] = new_t2
new_t2 += 1
for old in range( old + 1, old + 4 ):
remap[old] = new_t3
new_t3 += 1
elif e == elements - 1:
old = 12 + ( e - 1 ) * 9
for old in range( old, old + 3 ):
remap[old] = new_t1
new_t1 += 1
for old in range( old + 1, old + 3 ):
remap[old] = new_t2
new_t2 += 1
for old in range( old + 1, old + 2 ):
remap[old] = new_t3
new_t3 += 1
else:
old = 12 + ( e - 1 ) * 9
for old in range( old, old + 4 ):
remap[old] = new_t1
new_t1 += 1
for old in range( old + 1, old + 4 ):
remap[old] = new_t2
new_t2 += 1
for old in range( old + 1, old + 3 ):
remap[old] = new_t3
new_t3 += 1
ring.mapper.set_custom_ensemble_ordering( remap )
#==================================================================#
if height > 0.0 and radius > 0.0:
# generate parameters
theta_t1 = scipy.linspace(0, scipy.pi*2.0, elements * 4 + 1)
theta_t2 = scipy.linspace(0, scipy.pi*2.0, elements * 3 + 1)
theta_t3 = scipy.linspace(0, scipy.pi*2.0, elements * 2 + 1)
theta = [theta_t1, theta_t2, theta_t3]
Z = scipy.linspace( 0.0, height, 3 )
# generate parameters lists
xparam = []
yparam = []
zparam = []
for i in range( 3 ):
x = radius*scipy.cos(theta[i])
y = radius*scipy.sin(theta[i])
z = Z[i]
for i in range( len( theta[i] ) - 1 ):
xparam.append( x[i] )
yparam.append( y[i] )
zparam.append( z )
return ( ring, xparam, yparam, zparam )
else:
return ring
#==========================#
# ring of 2-triangle quads #
#==========================#
#
# 16 _17_18_19_20_21_22_23__ 16 radius[2]
# |\ |\ |\ |\ |
# | \ | \ | \ | \ |
# 8| 9 10 11 12 13 14 15 |8 radius[1]
# | \ | \ | \ | \ |
# |____\|____\|____\|____\|
# 0 1 2 3 4 5 6 7 0 radius[0]
def two_quad_ring( number_of_quads, height = None, radius = None ):
"""
number_of_quads defines the number of 2-triangle quads in the ring
( number of triangles / 2 ).
height and radius determine the x,y,z parameters returned.
radius can either be scalar, where the cylinder will have uniform
radius along its length, or a list of 3 values.
"""
# initialise main field ensemble
dimensions = 2
elements = number_of_quads
basis_type = 'triangular_quadratic_2d'
npoints = elements*6
ring = E.ensemble_field_function('2_quad_ring', dimensions, debug = 0)
ring.set_basis( basis_type )
ring.set_new_mesh('2_quad_ring')
# create 2 triangle quads for the ring and add to main field ensemble
for i in range( elements ):
ring.add_element( two_quad_patch() )
# connect up quads
for i in range( elements-1 ):
ring.connect_element_points( [(i,2), (i+1,0)] )
ring.connect_element_points( [(i,5), (i+1,3)] )
ring.connect_element_points( [(i,8), (i+1,6)] )
# join end of strip to start
ring.connect_element_points( [(i+1,2), (0,0)] )
ring.connect_element_points( [(i+1,5), (0,3)] )
ring.connect_element_points( [(i+1,8), (0,6)] )
ring.map_parameters()
#==================================================================#
# remap ensemble point numbering so that node numbering increase first
# up each column of nodes
remap = _two_quad_ring_remapper( number_of_quads )
ring.mapper.set_custom_ensemble_ordering( remap )
#==================================================================#
if height and radius:
# for quadratic quads, there are elements*2 nodes around the circle
# generate coordinates for nodes
if isinstance( radius, float ) or isinstance( radius, int ):
radius = [radius]*3
elif len( radius ) != 3:
print 'ERROR: radius must be scalar or 3 long'
return None
theta = scipy.linspace( 0.0, 2.0*scipy.pi, elements*2 + 1 )
zcoords = scipy.linspace( 0.0, height, 3 )
xparam = []
yparam = []
zparam = []
for row in range( 3 ):
xcoords = radius[row] * scipy.cos(theta)
ycoords = radius[row] * scipy.sin(theta)
for i in range( len( xcoords ) - 1 ):
xparam.append( [xcoords[i]] )
yparam.append( [ycoords[i]] )
zparam.append( [float(zcoords[row])] )
return ( ring, xparam, yparam, zparam )
else:
return ring
#========#
# sphere #
#========#
def sphere( azimuth_divs, incline_divs, radius, inclination_max ):
""" Full sphere is inclination_max = pi, else sphere is truncated.
Sphere mesh is composed of tri_hemispheres for the top and bottom
caps and three_quad_rings in between.
Orientation and ensemble point numbering of the rings are flipped at
the equator. Ensemble point numbering starts at the bottom and
increases latitudinally (around the sphere) before moving up
longitudinally.
Note: if inclination_max == pi, incline_divs must be even
"""
dimensions = 2
basis_type = 'triangular_quadratic_2d'
# initialise main field ensemble
sphere = E.ensemble_field_function('sphere', dimensions, debug = 0)
sphere.set_basis( basis_type )
sphere.set_new_mesh('sphere')
# determine number of tiers in the upper hemisphere
# assign tiers proportional to 90/inclination_max if inclination > 90
if inclination_max > scipy.pi/2.0:
upper_tiers = int( round( incline_divs * (scipy.pi/2.0) / inclination_max ) )
lower_tiers = incline_divs - upper_tiers
else:
upper_tiers = incline_divs
lower_tiers = 0
# rings and their number of 3-tri quad elements
ring_elements = {}
ring_counter = 0
if inclination_max == scipy.pi:
lower_rings = lower_tiers - 1
else:
lower_rings = lower_tiers
upper_rings = upper_tiers - 1
# if truncated sphere, return the number of points at the base of the sphere for connection
# their numbers will be 0 to connect_points - 1
connect_points = None
#==================================================================#
# add caps and rings
# lower hemisphere, node ordering need to be reversed
# if a full sphere
if inclination_max == scipy.pi:
# lower cap first
lower_cap = tri_hemisphere( 0.0, azimuth_divs )
#~ remap = {0:6, 1:7, 2:8, 3:2, 4:0, 5:1, 6:9, 7:10, 8:3, 9:11, 10:12, 11:4, 12:13, 13:14, 14:5, 15:15}
remap = _tri_hemisphere_reverse_mapper( azimuth_divs )
lower_cap.mapper.set_custom_ensemble_ordering( remap )
sphere.add_element( lower_cap )
# then lower rings
for i in range( lower_tiers - 1 ):
ring = three_quad_ring( azimuth_divs * 2**i, 0.0, 0.0 )
ring.mapper.set_custom_ensemble_ordering( _reverse_custom_mapping( ring.mapper._custom_ensemble_order ) )
sphere.add_element( ring )
ring_elements[ring_counter] = azimuth_divs * 2**i
ring_counter += 1
# if an incomplete sphere
else:
# just lower rings
for i in range( lower_rings ):
ring = three_quad_ring( azimuth_divs * 2**( (upper_rings - 1) - (lower_rings - 1 - i) ), 0.0, 0.0 )
ring.mapper.set_custom_ensemble_ordering( _reverse_custom_mapping( ring.mapper._custom_ensemble_order ) )
sphere.add_element( ring )
ring_elements[ring_counter] = azimuth_divs * 2**( (upper_rings - 1) - (lower_rings - 1 - i) )
ring_counter += 1
connect_points = ring_elements[0] * 2
# upper hemisphere
if upper_tiers > 1:
for i in range( upper_rings ):
sphere.add_element( three_quad_ring( azimuth_divs * 2**(upper_rings - 1 - i), 0.0, 0.0 ) )
ring_elements[ring_counter] = azimuth_divs * 2**(upper_rings - 1 - i)
ring_counter += 1
# upper cap
sphere.add_element( tri_hemisphere( 0.0, azimuth_divs ) )
#==================================================================#
# connect rings and caps
# connect lower hemisphere
element_i = 0
if inclination_max == scipy.pi:
# connect lower cap to closest ring, or upper cap
for i in range( azimuth_divs * 2 ):
if not sphere.connect_element_points( [(0, 1+azimuth_divs+i), (1, i)] ):
print 'ERROR: tri_shapes.sphere: connecting failed'
return None
element_i += 1
# connect lower rings
for lower_ring in range( lower_rings ):
start = ring_elements[lower_ring] * 5
for i in range( ring_elements[lower_ring] * 4 ):
if not sphere.connect_element_points( [(element_i, start+i), (element_i+1, i)] ):
print 'ERROR: tri_shapes.sphere: connecting failed:', [(element_i, start+i), (element_i+1, i)]
print 'start:', start
print 'i_range:', ring_elements[lower_ring] * 4
return None
element_i += 1
# connect upper rings and upper cap
for upper_ring in range( upper_rings ):
start = ring_elements[upper_ring + lower_rings] * 7
for i in range( ring_elements[upper_ring + lower_rings] * 2 ):
if not sphere.connect_element_points( [(element_i, start+i), (element_i+1, i)] ):
print 'ERROR: tri_shapes.sphere: connecting failed:', [(element_i, start+i), (element_i+1, i)]
print 'start:', start
print 'i_range:', ring_elements[upper_ring + lower_rings + 1] * 2
return None
element_i += 1
#==================================================================#
# map, no remap needed
sphere.map_parameters()
#==================================================================#
# generate parameters
xparams = []
yparams = []
zparams = []
phi = scipy.linspace( inclination_max, 0.0, incline_divs*2+1 )
zcoords = radius * scipy.cos( phi )
z_i = 0
# if lower cap
if inclination_max == scipy.pi:
# apex
xparams.append( [0.0] )
yparams.append( [0.0] )
zparams.append( [zcoords[0]] )
# 1st row of nodes
theta = scipy.linspace( 0, 2.0*scipy.pi, azimuth_divs + 1 )
xcoords = radius * scipy.cos( theta ) * scipy.sin( phi[1] )
ycoords = radius * scipy.sin( theta ) * scipy.sin( phi[1] )
for i in range( azimuth_divs ):
xparams.append( [xcoords[i]] )
yparams.append( [ycoords[i]])
zparams.append( [zcoords[1]] )
z_i = 2
# lower rings
for ring in range(lower_rings):
# for each row of nodes (lower 2 rows)
for row in range( 2 ):
theta = scipy.linspace( 0.0, 2.0*scipy.pi, ring_elements[ring] * (row+2) + 1 )
xcoords = radius * scipy.cos( theta ) * scipy.sin( phi[z_i] )
ycoords = radius * scipy.sin( theta ) * scipy.sin( phi[z_i] )
for i in range( ring_elements[ring] * (row+2) ):
xparams.append( [xcoords[i]] )
yparams.append( [ycoords[i]] )
zparams.append( [zcoords[z_i]] )
z_i += 1
# upper rings
for ring in range(upper_rings):
# for each row of nodes (lower 2 rows)
for row in range( 2 ):
theta = scipy.linspace( 0.0, 2.0*scipy.pi, ring_elements[lower_rings + ring] * (4-row) + 1 )
xcoords = radius * scipy.cos( theta ) * scipy.sin( phi[z_i] )
ycoords = radius * scipy.sin( theta ) * scipy.sin( phi[z_i] )
for i in range( ring_elements[lower_rings + ring] * (4-row) ):
xparams.append( [xcoords[i]] )
yparams.append( [ycoords[i]] )
zparams.append( [zcoords[z_i]] )
z_i += 1
# upper cap
for row in range(2):
theta = scipy.linspace( 0, 2.0*scipy.pi, azimuth_divs * (2 - row) + 1 )
xcoords = radius * scipy.cos( theta ) * scipy.sin( phi[z_i] )
ycoords = radius * scipy.sin( theta ) * scipy.sin( phi[z_i] )
for i in range( azimuth_divs * (2 - row) ):
xparams.append( [xcoords[i]] )
yparams.append( [ycoords[i]] )
zparams.append( [zcoords[z_i]] )
z_i += 1
# apex
xparams.append( [0.0] )
yparams.append( [0.0] )
zparams.append( [zcoords[-1]] )
#==================================================================#
return (sphere, xparams, yparams, zparams, connect_points)
#================#
# tri_hemisphere #
#================#
#
# 2
# 3 | 1
# 9
# |
# 4--10--12---8--0
# |
# 11
# 5 | 7
# 6
#
def tri_hemisphere(radius, elements):
dimensions = 2
element_type = 'tri6'
basis_type = 'triangular_quadratic_2d'
# initialise main field ensemble
hemi = E.ensemble_field_function('hemisphere', dimensions, debug = 0)
hemi.set_basis( basis_type )
hemi.set_new_mesh('hemisphere')
hemi.create_elements( element_type, elements )
# connect elements
hemi.connect_element_points( [ (i,4) for i in range( elements ) ] ) # apex
for i in range( elements-1 ):
hemi.connect_element_points( [(i,3), (i+1,5)] )
hemi.connect_element_points( [(i,2), (i+1,0)] )
hemi.connect_element_points( [(i+1,3), (0,5)] )
hemi.connect_element_points( [(i+1,2), (0,0)] )
hemi.map_parameters()
#==================================================================#
# remap
remap = {}
# 1st elements
remap[0] = 0
remap[1] = 1
remap[2] = 2
remap[5] = elements * 2
remap[3] = elements * 2 + 1
# other elements
old_t1 = 6
old_t2 = 8
new_t1 = 3
new_t2 = elements * 2 + 2
for i in range( 1, elements ):
remap[old_t1] = new_t1
if i < elements - 1:
remap[old_t1 + 1] = new_t1 + 1
remap[old_t2] = new_t2
old_t1 += 3
new_t1 += 2
old_t2 += 3
new_t2 += 1
# apex
remap[4] = new_t2 - 1
hemi.mapper.set_custom_ensemble_ordering( remap )
#==================================================================#
if radius > 0.0:
# generate parameters
theta = scipy.linspace( 0, scipy.pi/2.0, 3 )
phi = scipy.linspace(0, scipy.pi*2.0, elements * 2 + 1)
xparam = []
yparam = []
zparam = []
# tier 1
z = radius * scipy.sin( theta[0] )
for i in range( elements * 2 ):
xparam.append( [ radius * scipy.cos( theta[0] ) * scipy.cos( phi[i] ) ] )
yparam.append( [ radius * scipy.cos( theta[0] ) * scipy.sin( phi[i] ) ] )
zparam.append( [ z ] )
# tier 2
z = radius * scipy.sin( theta[1] )
for i in range( 0, elements * 2, 2 ):
xparam.append( [ radius * scipy.cos( theta[1] ) * scipy.cos( phi[i] ) ] )
yparam.append( [ radius * scipy.cos( theta[1] ) * scipy.sin( phi[i] ) ] )
zparam.append( [ z ] )
# apex
xparam.append( [0.0] )
yparam.append( [0.0] )
zparam.append( [ radius * scipy.sin( theta[2] ) ])
return (hemi, xparam, yparam, zparam )
else:
return hemi
def four_tri_patch_hemisphere( radius, elements ):
dimensions = 2
basis_type = 'triangular_quadratic_2d'
# initialise main field ensemble
hemi = E.ensemble_field_function('4_tri_patch_hemisphere', dimensions, debug = 0)
hemi.set_basis( basis_type )
hemi.set_new_mesh('4_tri_patch_hemisphere')
for i in range( elements ):
hemi.add_element( four_tri_patch() )
# connect elements
hemi.connect_element_points( [ (i,14) for i in range( elements ) ] ) # apex
for i in range( elements-1 ):
hemi.connect_element_points( [(i,4), (i+1,0)] )
hemi.connect_element_points( [(i,8), (i+1,5)] )
hemi.connect_element_points( [(i,11), (i+1,9)] )
hemi.connect_element_points( [(i,13), (i+1,12)] )
hemi.connect_element_points( [(i+1,4), (0,0)] )
hemi.connect_element_points( [(i+1,8), (0,5)] )
hemi.connect_element_points( [(i+1,11), (0,9)] )
hemi.connect_element_points( [(i+1,13), (0,12)] )
hemi.map_parameters()
#==================================================================#
# remap
remap = _four_tri_patch_hemisphere_remapper( elements )
hemi.mapper.set_custom_ensemble_ordering( remap )
#==================================================================#
if radius > 0.0:
# generate parameters
theta = scipy.linspace( 0.0, scipy.pi/2.0, 5 )
phi_t1 = scipy.linspace(0, scipy.pi*2.0, elements * 4 + 1)
phi_t2 = scipy.linspace(0, scipy.pi*2.0, elements * 3 + 1)
phi_t3 = scipy.linspace(0, scipy.pi*2.0, elements * 2 + 1)
phi_t4 = scipy.linspace(0, scipy.pi*2.0, elements * 1 + 1)
phi = [ phi_t1, phi_t2, phi_t3, phi_t4 ]
xparam = []
yparam = []
zparam = []
for i in range( len(theta) - 1 ):
z = radius * scipy.sin( theta[i] )
cos_theta = scipy.cos( theta[i] )
for p in range( len( phi[i] ) - 1 ):
xparam.append( [ radius * cos_theta * scipy.cos( phi[i][p] ) ] )
yparam.append( [ radius * cos_theta * scipy.sin( phi[i][p] ) ] )
zparam.append( [ z ] )
# apex
xparam.append( [0.0] )
yparam.append( [0.0] )
zparam.append( [ radius * scipy.sin( theta[-1] ) ])
return (hemi, xparam, yparam, zparam)
else:
return hemi
#=================#
# private mappers #
#=================#
def _reverse_custom_mapping( map ):
# map is a dictionary
max_key = max(map.keys())
map_r = {}
for k in map.keys():
map_r[k] = max_key - map[k]
return map_r
def _tri_hemisphere_reverse_mapper( elements ):
# maps tri_hemispheres in reverse (starting from apex) for use in the
# sphere generator
remap = {}
# 1st elements
remap[0] = elements + 1
remap[1] = elements + 2
remap[2] = elements + 3
remap[5] = 1
remap[3] = 2
remap[4] = 0
# other elements
old_t1 = 6
old_t2 = 8
new_t1 = elements + 4
new_t2 = 3
for i in range( 1, elements ):
remap[old_t1] = new_t1
if i < elements - 1:
remap[old_t1 + 1] = new_t1 + 1
remap[old_t2] = new_t2
old_t1 += 3
new_t1 += 2
old_t2 += 3
new_t2 += 1
return remap
def _four_tri_patch_hemisphere_remapper( elements ):
remap = {}
old_t1 = 0
old_t2 = 5
old_t3 = 9
old_t4 = 12
new_t1 = 0
new_t2 = elements * 4
new_t3 = new_t2 + 3 * elements
new_t4 = new_t3 + 2 * elements
# 1st element
for old_t1 in range( old_t1, old_t1 + 5 ):
remap[old_t1] = new_t1
new_t1 += 1
for old_t2 in range( old_t2, old_t2 + 4 ):
remap[old_t2] = new_t2
new_t2 += 1
for old_t3 in range( old_t3, old_t3 + 3 ):
remap[old_t3] = new_t3
new_t3 += 1
for old_t4 in range( old_t4, old_t4 + 2 ):
remap[old_t4] = new_t4
new_t4 += 1
# other elements
for e in range( 1, elements ):
old_t1 = 15 + ( e - 1 ) * 10
old_t2 = 19 + ( e - 1 ) * 10
old_t3 = 22 + ( e - 1 ) * 10
old_t4 = 24 + ( e - 1 ) * 10
if e < elements - 1:
for old_t1 in range( old_t1, old_t1 + 4 ):
remap[old_t1] = new_t1
new_t1 += 1
for old_t2 in range( old_t2, old_t2 + 3 ):
remap[old_t2] = new_t2
new_t2 += 1
for old_t3 in range( old_t3, old_t3 + 2 ):
remap[old_t3] = new_t3
new_t3 += 1
for old_t4 in range( old_t4, old_t4 + 1 ):
remap[old_t4] = new_t4
new_t4 += 1
else:
for old_t1 in range( old_t1, old_t1 + 3 ):
remap[old_t1] = new_t1
new_t1 += 1
for old_t2 in range( old_t2 - 1, old_t2 + 1 ):
remap[old_t2] = new_t2
new_t2 += 1
for old_t3 in range( old_t3 - 2, old_t3 - 1 ):
remap[old_t3] = new_t3
new_t3 += 1
remap[14] = elements * 10
return remap
def _two_quad_ring_remapper( elements ):
remap = {}
old = scipy.array( [9, 11, 13] )
old1 = scipy.array( [0, 3, 6] )
new = scipy.array( [0, elements * 2, elements * 4] )
for e in range( 0, elements ):
# 1st element
if e == 0:
for i in range( 3 ):
remap[old1[0]] = new[0]
remap[old1[1]] = new[1]
remap[old1[2]] = new[2]
new += 1
old1 += 1
# last element
elif e == elements - 1:
oldn = old + (e-1) * 6
remap[oldn[0]] = new[0]
remap[oldn[0]+1] = new[1]
remap[oldn[0]+2] = new[2]
else:
oldn = old + (e-1) * 6
remap[oldn[0]] = new[0]
remap[oldn[1]] = new[1]
remap[oldn[2]] = new[2]
remap[oldn[0] + 1] = new[0] + 1
remap[oldn[1] + 1] = new[1] + 1
remap[oldn[2] + 1] = new[2] + 1
new += 2
return remap
#==================#
# femur primitives #
#==================#
# head and neck =======================================================#
def head_neck( h_r, n_l, n_r = None, h_adiv = 5, h_idiv = 3, h_maxi = 3.0/4.0*scipy.pi, n_ldiv = 2 ):
""" A truncated 3/4 sphere(head) and a truncated cone (neck)
origin at centre of sphere
parameters: h_r = head radius
n_l = neck length
n_r = neck radius at the base of the cone, if
none, = radius at base of sphere
h_adiv = head sphere azimuth divisions
h_idiv = head sphere inclination divisions
h_maxi = head sphere maximum inclination
n_ldiv = neck cone longitudinal divisions
"""
h_r = float(h_r)
n_l = float(n_l)
# initialise main field ensemble
dimensions = 2
basis_type = 'triangular_quadratic_2d'
head_neck = E.ensemble_field_function('head_neck', dimensions, debug = 0)
head_neck.set_basis( basis_type )
head_neck.set_new_mesh('head_neck_mesh')
xparams = []
yparams = []
zparams = []
# generate head sphere ============================================#
( h_sphere, h_x, h_y, h_z, h_connect_points_n ) = sphere( h_adiv, h_idiv, h_r, h_maxi )
# ensemble points at the base of the sphere for connection and their radius
h_connect_points = range( h_connect_points_n )
h_connect_r = h_r * scipy.sin( h_maxi )
h_connect_z = h_z[0][0]
if not n_r:
n_r = h_connect_r
else:
n_r = float(n_r)
# generate truncated cone =========================================#
# generate radius values
n_r_range = scipy.linspace( n_r, h_connect_r, n_ldiv * 2 + 1)
# generate two_quad_rings from base of cone up
for i in range( n_ldiv ):
ring_r = n_r_range[ i*2: i*2 + 3 ]
(ring, ring_x, ring_y, ring_z) = two_quad_ring( h_connect_points_n/2, n_l/n_ldiv, ring_r )
head_neck.add_element( ring )
# keep 1st 2 rows of parameters values
xparams += ring_x[ 0:h_connect_points_n * 2 ]
yparams += ring_y[ 0:h_connect_points_n * 2 ]
# translate in z
z = ring_z[ 0:h_connect_points_n * 2 ]
z_shift = h_connect_z - n_l/n_ldiv * ( n_ldiv - i )
z = list( scipy.add( z, z_shift ) )
z = [ list(i) for i in z ]
zparams += z
# add sphere to mesh ==============================================#
head_neck.add_element( h_sphere )
xparams += h_x
yparams += h_y
zparams += h_z
# connect top of truncated cone to base of sphere
for element in range( n_ldiv ):
for i in range( h_connect_points_n ):
head_neck.connect_element_points( [(element, h_connect_points_n * n_ldiv + i), (element + 1, i)] )
# map
head_neck.map_parameters()
connect_points = h_connect_points
return ( head_neck, xparams, yparams, zparams, connect_points )
| Python |
"""
========================================================================
FILE: mapper.py
LAST MODIFIED: 01 September 2009
DESCRIPTION:
class to create maps mapping ensemble parameters to element point
parameters and vice-versa.
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
import scipy
class mapper:
""" Class to create maps mapping ensemble parameters to element point
parameters and vice-versa.
"""
def __init__( self, debug = 0 ):
self.mesh = None
self._ensemble_to_element_map = {} # { global_point_number: { element_number: {point_number: weighting}, ... } }
self._element_to_ensemble_map = {} # { element_number: { point_number: [[ global_point_number, [weightings] ], [...], ...] } }
self.number_of_ensemble_points = 0
self.number_of_dof = 0
self._custom_ensemble_order = None # { self generated number: user assigned number }
self.debug = debug
return
#==================================================================#
def set_parent_field( self, parent_field ):
""" set new parent field on which mapping is based.
parent field should contain toplogical, and basis information
about itself and child fields.
"""
self.field = parent_field
self.number_of_ensemble_points = self.field.mesh.get_number_of_ensemble_points()
if not self.number_of_ensemble_points:
print 'ERROR: mapper.set_parent_field: empty parent mesh'
return
else:
# initialise ensemble to element map
for i in range( self.number_of_ensemble_points ):
self._ensemble_to_element_map[i] = {}
# initialise element to ensemble map
for i in range( len( self.field.mesh.elements ) ):
# initialise element entries
self._element_to_ensemble_map[i] = {}
for j in range( self.field.mesh.elements[i].get_number_of_ensemble_points() ):
# initialise element point entries for each element
self._element_to_ensemble_map[i][j] = []
return 1
#==================================================================#
def do_mapping( self ):
""" map the current mesh topology
"""
gp = 0 # global points number
assigned = [] # list of element points already assigned a global number
ep = self.field.mesh.connectivity.keys() # list of all element points and hanging points
ep.sort()
i = 0
if self.debug:
print 'sorted element points:', ep
# account for points connected to hanging nodes
while ep[i][0] == -1:
assigned += self.field.mesh.connectivity[ep[i]]
i += 1
# map conventional points
for j in range(i, len( ep ) ):
if self.debug:
print 'mapping ep:', ep[j]
# loop through each element point in the connectivity dict
(e, p) = ep[j]
# check if point has already been assigned a global number
if (e, p) not in assigned:
if self.debug:
print 'assigning global', gp, 'to', [(e,p)] + self.field.mesh.connectivity[(e,p)]
# update ensemble to element map
try:
self._ensemble_to_element_map[gp][e][p] = 1.0
except KeyError:
self._ensemble_to_element_map[gp][e] = { p: 1.0 }
# update element to ensemble map
self._element_to_ensemble_map[e][p].append( [ gp, [1.0] ] )
assigned.append( (e,p) )
# map points connected to the current element point
for [ec, pc] in self.field.mesh.connectivity[(e,p)]:
# update ensemble to element map
try:
self._ensemble_to_element_map[gp][ec][pc] = 1.0
except KeyError:
self._ensemble_to_element_map[gp][ec] = { pc: 1.0 }
# update element to ensemble map
self._element_to_ensemble_map[ec][pc].append( [ gp, [1.0] ] )
assigned.append( (ec, pc) )
if self.debug:
print 'assigned:', assigned
gp += 1
if self.debug:
print 'element to ensemble map:', self._element_to_ensemble_map
# map hanging points
if self.debug:
print 'i:', i
# for each hanging point
for h in range( i ):
hp = self.field.mesh.hanging_points[h]
# get its host_element and element_coord
host_element = hp.get_host_element()
host_element_c = hp.get_element_coordinates()
# find the ensemble points associated with the host element
host_gp = []
for element_point in self._element_to_ensemble_map[host_element].keys():
for [g, w] in self._element_to_ensemble_map[host_element][element_point]:
host_gp.append(g)
# calculate weightings using basis
# if local
weights = self.field.basis.eval( host_element_c )
if self.debug:
print 'host_element_c:', host_element_c, 'weights:', weights
print 'host_gp:', host_gp
if isinstance( weights, int ):
print 'ERROR: mapper._map_ensemble_to_element: unable to evaluate weights'
return
else:
# update maps for connected element points
for [e,p] in self.field.mesh.connectivity[ ep[h] ]:
for host_gp_i in range( len( host_gp ) ):
# update ensemble to element map
try:
self._ensemble_to_element_map[ host_gp[host_gp_i] ][e][p] = weights[ host_gp_i ]
except KeyError:
self._ensemble_to_element_map[ host_gp[host_gp_i] ][e] = { p: weights[ host_gp_i ] }
# update element to ensemble map
self._element_to_ensemble_map[e][p].append( [ host_gp[host_gp_i], [weights[ host_gp_i ]] ] )
return 1
#==================================================================#
def remove_element( self, element_number ):
""" removes element from the _element_to_ensemble_map
"""
if element_number in self._element_to_ensemble_map.keys():
# get element point to ensemble points mapping
ep_map = self._element_to_ensemble_map[ element_number ]
ensemble_points = []
for element_point in ep_map.values():
ensemble_points += [ p[0] for p in element_point ]
# remove entries in ensemble_to_element_map
for ensemble_point in ensemble_points:
del self._ensemble_to_element_map[ensemble_point][element_number]
# remove mapping in _element_to_ensemble_map
del self._element_to_ensemble_map[ element_number ]
return 1
else:
print 'ERROR: mapper.remove_element: element', element_number, 'does not exist'
return
#==================================================================#
def get_ensemble_point_element_points( self, ensemble_point_number ):
""" returns a list of ( element n, element point n ) mapped to the
given ensemble_point_number
"""
try:
element_map = self._ensemble_to_element_map[ensemble_point_number]
except KeyError:
print 'ERROR: mapper.get_ensemble_point_number: invalid ensemble point number'
return None
else:
element_points = []
for element in element_map:
for point in element_map[element]:
element_points.append( (element, point) )
return element_points
#==================================================================#
def get_element_parameters( self, element_number, parameters ):
""" Uses mapping to return the element parameters for the
required element.
"""
# get mapping for specified element
try:
element_map = self._element_to_ensemble_map[ element_number ]
except IndexError:
print 'ERROR: mapper.get_element_parameters: invalid element_number'
return None
if len( parameters ) != self.get_number_of_ensemble_points():
print 'ERROR: mapper.get_element_parameters: incorrect number of parameters. Require', self.get_number_of_ensemble_points()
return None
# get list of element points
points = element_map.keys()
points.sort()
element_parameters = []
# for each element point
for element_point in points:
mapped_values = []
# for each global point mapped to this element point
for [g, w] in element_map[ element_point ]:
# if custom ensemble point ordering, map g to the right ensemble point
if self._custom_ensemble_order:
g = self._custom_ensemble_order[g]
# calculated the weighted contribution of this global point
mapped_values.append( scipy.multiply( parameters[g], w ) )
# sum contributions and append element_point parameter to element_parameters
element_parameters.append( list( scipy.sum( mapped_values, axis = 0 ) ) )
return element_parameters
#==================================================================#
def get_number_of_ensemble_points( self ):
return self.number_of_ensemble_points
#==================================================================#
def get_number_of_dof( self ):
return self.number_of_dof
#==================================================================#
def set_custom_ensemble_ordering( self, ordering ):
""" defines custom numbering order to ensemble points
"""
# check for correct length
if len( ordering ) != self.number_of_ensemble_points:
print 'ERROR: mapper.set_custom_ensemble_ordering: wrong number of entries in new ordering. Require:', self.number_of_ensemble_points, ', got:', len( ordering )
return
else:
self._custom_ensemble_order = dict(ordering)
return 1
| Python |
"""
========================================================================
FILE: basis.py
LAST MODIFIED: 20 August 2009
DESCRIPTION:
Basis classes and constructor for creating and returning a basis
instance of the required dimensionality and basis
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
import scipy
# basis matrices of implemented bases for tensor product basis
basis_matrices_map = {'linear_lagrange': scipy.array( [[1.0, -1.0],\
[0.0, 1.0]] ),\
'quadratic_lagrange': scipy.array( [[1.0, -3.0, 2.0],\
[0.0, 4.0, -4.0],\
[0.0, -1.0, 2.0]] ),\
'cubic_hermite': scipy.array( [[1.0, 0.0, -3.0, 2.0],\
[0.0, 1.0, -2.0, 1.0],\
[0.0, 0.0, 3.0, -2.0],\
[0.0, 0.0, -1.0, 1.0]] ) }
#=======================================================================#
def make_basis( dimensions, basis_types ):
""" Constructor function for making a basis object
basis_types should be a list or tuple of strings
"""
global implemented_bases
if basis_types[0] == 'triangular_linear_2d':
B = triangular_linear_2d()
elif basis_types[0] == 'triangular_quadratic_2d':
B = triangular_quadratic_2d()
else:
# check for right number of basis_types for specified dimensionality
if len( basis_types ) != dimensions:
print 'ERROR: wrong number of basis_types for dimensions'
return 0
else:
basis_matrices = []
final_type = ''
for type in basis_types:
if type not in basis_matrices_map.keys():
print 'ERROR: unrecognised basis', type
return 0
else:
basis_matrices.append( basis_matrices_map[type] )
final_type += ' '+type
# instantiate basis object
B = tensor_product_basis( dimensions, basis_matrices, type )
return B
#======================================================================#
class tensor_product_basis:
""" Tensor product basis object for quad elements
dimension: number of dimensions
basis_matrices: a list of tensor product basis matrices, one for each dimension
type: a string containing the names of basis in each dimension
"""
def __init__( self, dimensions, basis_matrices, type ):
self.dimensions = dimensions # integer of number of dimensions
self.basis_matrices = basis_matrices # list of rank 2 arrays
self.type = type # string of basis type?
self.basis_orders = [ (b.shape[0] - 1) for b in self.basis_matrices ]
def eval( self, x ):
# evaluates the basis function at the given element coordinates
# returns a list of values to be dot multiplied with nodal values
# x should be a list of lists of xi coordinates
# e.g. [ xi1 , xi2 ,...]
# check x to be of right dimensionality
if len( x ) != self.dimensions:
print 'ERROR: wrong number of xi, need', self.dimensions
return None
else:
# get phis for each dimension
phid = []
for i in range( self.dimensions ):
x_vector = [ x[i]**p for p in range( self.basis_orders[i] + 1 ) ]
phid.append( scipy.dot( self.basis_matrices[i], x_vector ) )
# do tensor product using kron
# reverse dimensions to get same implementation as cmiss
phi = phid[0]
if self.dimensions > 1:
for d in range( 1, self.dimensions ):
phi = scipy.kron( phid[d], phi )
return phi
#======================================================================#
class triangular_linear_2d:
""" Triangular element bases are hard coded for now
"""
def __init__( self ):
self.dimensions = 2
self.type = 'triangular_linear_2d'
self.basis_order = 1
def eval( self, x ):
phi = [0.0]*3
phi[0] = 1 - x[0] - x[1]
phi[1] = x[0]
phi[2] = x[1]
return phi
class triangular_quadratic_2d:
""" Triangular element bases are hard coded for now
"""
def __init__( self ):
self.dimensions = 2
self.type = 'triangular_quadratic_2d'
self.basis_order = 2
def eval( self, x ):
phi = [0.0]*6
phi[0] = ( 1- x[0] - x[1] ) * ( 2 * ( 1 - x[0] - x[1] ) - 1 )
phi[1] = 4 * ( 1 - x[0] - x[1] ) * x[0]
phi[2] = x[0] * ( 2*x[0] - 1 )
phi[3] = 4 * x[0] * x[1]
phi[4] = x[1] * ( 2*x[1] - 1 )
phi[5] = 4 * x[1] * ( 1 - x[0] - x[1] )
return phi
| Python |
"""
========================================================================
FILE: geometric_field_interactor.py
LAST MODIFIED: 20 September 2009
DESCRIPTION:
classes and functions to interact with geometric_fields in mayavi2
========================================================================
"""
"""
BEGIN LICENSE BLOCK
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this file are subject to the Mozilla Public License Version
1.1 (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.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is fieldwork.
The Initial Developer of the Original Code is Ju Zhang.
Portions created by the Initial Developer are Copyright (C) 2009
the Initial Developer. All Rights Reserved.
Contributor(s):
Alternatively, the contents of this file may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this file only
under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this file under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this file under
the terms of any one of the MPL, the GPL or the LGPL.
END LICENSE BLOCK
"""
from enthought.mayavi import mlab
from enthought.tvtk.api import tvtk
import scipy
class point_picker(object):
"""observers methods for a mayavi scene interactor.
Applied logic to make it record the picked position only
if the mouse has not moved between lmb press and release.
picks up to a user defined number of points before notifying a
parent class.
"""
mouse_mvt = False
def __init__(self, picker, points_plot, figure, parent):
self.picker = picker
self.points_plot = points_plot
self.parent = parent
self.figure = figure
self.picked_points = []
def set_number_of_points_to_pick( self, n ):
""" clears the list of picked points and defines how many points
to pick before calling the parent's _picking_done method """
self.picked_points = []
self.n = n
def on_button_press(self, obj, evt):
self.mouse_mvt = False
def on_mouse_move(self, obj, evt):
self.mouse_mvt = True
def on_button_release(self, obj, evt):
""" if left mouse button has not moved, gets picked position
from scene pointpicker and calculates the closest data point.
records this data point until the number of recorded data points
reaches self.n, where it calls self.parent._picking_done() """
if not self.mouse_mvt:
x, y = obj.GetEventPosition()
self.picker.pick((x, y, 0), self.figure.scene.renderer)
# calculate distance to all data points from picked point
tmp = ( self.points_plot.mlab_source.points - self.picker.pick_position ) ** 2.0
# find nearest data point
nearest_point = tmp.sum(axis = 1).argmin()
print 'point:', nearest_point
self.picked_points.append( nearest_point )
print 'points picked:', self.picked_points
if len( self.picked_points ) == self.n:
print 'adding element...'
self.parent._picking_done()
self.mouse_mvt = False
return
self.mouse_mvt = False
class element_adder( object ):
""" Class for interactively adding an element to a geometric field
by clicking on the geometric points the new element's element points
will connect to. Initialise with the geometric_field object.
"""
def __init__( self, geometric_field ):
self.gf = geometric_field
self.element = None
# initialise plot
self.figure = mlab.figure(1)
self.points_plot = self.gf._plot_points()
self.field_plot = self.gf._plot_field( 10, glyph = 'sphere' )
# initialise point_picker
self.picker = point_picker( self.figure.scene.picker.pointpicker,
self.points_plot, self.figure, self )
self.figure.scene.interactor.add_observer('LeftButtonPressEvent',
self.picker.on_button_press)
self.figure.scene.interactor.add_observer('MouseMoveEvent',
self.picker.on_mouse_move)
self.figure.scene.interactor.add_observer('LeftButtonReleaseEvent',
self.picker.on_button_release)
def add_element( self, element ):
""" sets the point_picker for the user to select the required
number of points """
self.element = element
# get number of points needed
element_points = self.element.get_number_of_ensemble_points()
print 'element requires', element_points, 'points.'
self.picker.set_number_of_points_to_pick( element_points )
mlab.show()
def _picking_done( self ):
""" once picking is done, add the element with the picked point
numbers. Re-draws the field plot with the new element """
if self.gf.add_element( self.element, self.picker.picked_points ):
print 'element_added'
self.field_plot.remove()
self.field_plot = self.gf._plot_field( 10, glyph = 'sphere' )
return 1
| Python |
# ring of a triangle strip in 3D space, centered at (0,0,0)
# element 0 starts at (1,0,0)
#!/usr/bin/env python
from scipy import *
from enthought.mayavi import mlab
import sys
sys.path.append( '../' )
from field import template_fields
from field import geometric_field
# ring parameters
height = 10
radius = [10,5,10]
elements = 4
eval_density = 20
# make ring and parameters
(ring, xparam, yparam, zparam) = template_fields.two_quad_ring( elements, height, radius )
# evaluate
x = ring.evaluate_field_in_mesh( eval_density, xparam )
x = array(x).flatten()
y = ring.evaluate_field_in_mesh( eval_density, yparam )
y = array(y).flatten()
z = ring.evaluate_field_in_mesh( eval_density, zparam )
z = array(z).flatten()
#~ plot.figure()
#~ plot.hold(True)
#~
#~ # plot field over mesh
#~ plot.scatter(x,y)
#~
#~ # plot ensemble nodes
#~ plot.scatter( array(xparam).flatten(), array(yparam).flatten(), marker = 's', s = 100, c='r' )
#~
#~ plot.show()
#~ a = mlab.orientationaxes()
p = mlab.points3d( x,y,z, mode = 'sphere', scale_factor = 0.5 )
n = mlab.points3d( xparam, yparam, zparam, mode = 'sphere', scale_factor = 1.0, color = (1,0,0) )
mlab.show()
| Python |
# geometric test using the head_neck geometry
#!/usr/bin/env python
from scipy import *
from enthought.mayavi import mlab
import sys
sys.path.append( '../' )
from field import template_fields
from field import geometric_field
from field.topology import element_types
from interactive import geometric_field_interactor as interactor
# head neck parameters
h_r = 20.0
n_l = 30.0
n_r = None
eval_density = 10
# instantiate a neck_neck field
(head_neck, xparam, yparam, zparam, cp) = template_fields.head_neck( h_r, n_l, n_r, )
# instantiate a geometric field with the head_neck field and parameters
gf = geometric_field.geometric_field( 'test', 3, head_neck )
gf.set_field_parameters( [xparam, yparam, zparam] )
# add some points and store their point numbers in p
p = []
p.append( gf.add_geometric_point([[14.0],[6.0],[-50.0]], name = 'test1') )
p.append( gf.add_geometric_point([[13.4],[10.3],[-55.0]], name = 'test2') )
p.append( gf.add_geometric_point([[6.0],[13.0],[-50.0]], name = 'test3') )
# create a quadratic triangular element
element = element_types.create_element( 'tri6' )
# add element to mesh using the interactor
adder = interactor.element_adder( gf )
adder.add_element( element )
| Python |
# hemi of a triangle strip in 3D space, centered at (0,0,0)
# element 0 starts at (1,0,0)
#!/usr/bin/env python
from scipy import *
from enthought.mayavi import mlab
import sys
sys.path.append( '../' )
from field import template_fields
from field import geometric_field
# hemi parameters
radius = 10.0
elements = 5
eval_density = 20
# make hemi and parameters
#~ (hemi, xparam, yparam, zparam) = template_fields.tri_hemisphere( radius, elements )
(hemi, xparam, yparam, zparam) = template_fields.four_tri_patch_hemisphere( radius, elements )
# evaluate
x = hemi.evaluate_field_in_mesh( eval_density, xparam )
x = array(x).flatten()
y = hemi.evaluate_field_in_mesh( eval_density, yparam )
y = array(y).flatten()
z = hemi.evaluate_field_in_mesh( eval_density, zparam )
z = array(z).flatten()
#~ plot.figure()
#~ plot.hold(True)
#~
#~ # plot field over mesh
#~ plot.scatter(x,y)
#~
#~ # plot ensemble nodes
#~ plot.scatter( array(xparam).flatten(), array(yparam).flatten(), marker = 's', s = 100, c='r' )
#~
#~ plot.show()
#~ a = mlab.orientationaxes()
p = mlab.points3d( x,y,z, mode = 'sphere', scale_factor = 0.5)
n = mlab.points3d( xparam, yparam, zparam, mode = 'sphere', scale_factor = 1.0, color = (1,0,0) )
mlab.show()
| Python |
# geometric test using the head_neck geometry
#!/usr/bin/env python
from scipy import *
from enthought.mayavi import mlab
import sys
sys.path.append( '../' )
from field import template_fields
from field import geometric_field
from field.topology import element_types
# head neck parameters
h_r = 20.0
n_l = 30.0
n_r = None
eval_density = 10
# instantiate a neck_neck field
(head_neck, xparam, yparam, zparam, cp) = template_fields.head_neck( h_r, n_l, n_r, )
# instantiate a geometric field with the head_neck field and parameters
gf = geometric_field.geometric_field( 'test', 3, head_neck )
gf.set_field_parameters( [xparam, yparam, zparam] )
# add some points and store their point numbers in p
p = []
p.append( gf.add_geometric_point([[14.0],[6.0],[-50.0]], name = 'test1') )
p.append( gf.add_geometric_point([[13.4],[10.3],[-55.0]], name = 'test2') )
p.append( gf.add_geometric_point([[6.0],[13.0],[-50.0]], name = 'test3') )
# create a quadratic triangular element
element = element_types.create_element( 'tri6' )
# add element to mesh
p.reverse()
epoints = [0,1,2] + p
gf.add_element( element, epoints, 1 )
gf.display_geometric_field( eval_density )
| Python |
# head_neck mesh generation test
#!/usr/bin/env python
from scipy import *
from enthought.mayavi import mlab
import sys
sys.path.append( '../' )
from field import template_fields
from field import geometric_field
# head neck parameters
h_r = 20.0
n_l = 30.0
n_r = None
eval_density = 20
# make hemi and parameters
(head_neck, xparam, yparam, zparam, cp) = template_fields.head_neck( h_r, n_l, n_r, )
# evaluate
x = head_neck.evaluate_field_in_mesh( eval_density, xparam )
x = array(x).flatten()
y = head_neck.evaluate_field_in_mesh( eval_density, yparam )
y = array(y).flatten()
z = head_neck.evaluate_field_in_mesh( eval_density, zparam )
z = array(z).flatten()
p = mlab.points3d( x,y,z, mode = 'point', scale_factor = 0.5)
n = mlab.points3d( xparam, yparam, zparam, mode = 'sphere', scale_factor = 1.0, color = (1,0,0) )
# label ensemble points
labels = range( len(xparam) )
for i in range( len(labels ) ):
mlab.text( xparam[i][0], yparam[i][0], str(labels[i]), z = zparam[i][0], line_width = 0.01, width = 0.01 )
mlab.show()
| Python |
# sphere mesh generation test
#!/usr/bin/env python
from scipy import *
from enthought.mayavi import mlab
import sys
sys.path.append( '../' )
from field import template_fields
from field import geometric_field
from field.topology import element_types
# sphere parameters
azimuth_divs = 5
incline_divs = 3
radius = 10.0
inclination_max = pi*3/4
eval_density = 20
# make hemi and parameters
(sphere, xparam, yparam, zparam, c) = template_fields.sphere( azimuth_divs, incline_divs, radius, inclination_max )
sphere.subfields[1].remove_element(1)
#~ sphere.remove_element(1)
# evaluate
x = sphere.evaluate_field_in_mesh( eval_density, xparam )
x = array(x).flatten()
y = sphere.evaluate_field_in_mesh( eval_density, yparam )
y = array(y).flatten()
z = sphere.evaluate_field_in_mesh( eval_density, zparam )
z = array(z).flatten()
p = mlab.points3d( x,y,z, mode = 'point', scale_factor = 0.5)
n = mlab.points3d( xparam, yparam, zparam, mode = 'sphere', scale_factor = 1.0, color = (1,0,0) )
mlab.show()
| Python |
# geometric test using the head_neck geometry
# tests both methods of adding elements - passing the points they are
# going to connect to, and their geometric parameters
#!/usr/bin/env python
from scipy import *
from enthought.mayavi import mlab
import sys
sys.path.append( '../' )
from field import template_fields
from field import geometric_field
from field.topology import element_types
# head neck parameters
h_r = 20.0
n_l = 30.0
n_r = None
eval_density = 10
# instantiate a new geometric_field with an empty 2D ensemble_field
gf = geometric_field.geometric_field( 'test', 3, field_dimensions = 2, field_basis = 'triangular_quadratic_2d' )
# make a head_neck mesh (ensemble_field + precomputed parameters)
(head_neck, xparam, yparam, zparam, cp) = template_fields.head_neck( h_r, n_l, n_r, )
# add head_mesh mesh and parameters to the geometric field
gf.add_element_with_parameters( head_neck, [xparam, yparam, zparam] )
# add some points and store their point numbers in p
p = []
p.append( gf.add_geometric_point([[14.0],[6.0],[-50.0]], name = 'test1') )
p.append( gf.add_geometric_point([[13.4],[10.3],[-55.0]], name = 'test2') )
p.append( gf.add_geometric_point([[6.0],[13.0],[-50.0]], name = 'test3') )
# create a quadratic triangular element
e_1 = element_types.create_element( 'tri6' )
# add element to mesh by specifying points
p.reverse()
epoints = [0,1,2] + p
gf.add_element( e_1, epoints, 1 )
# create another element
e_2 = element_types.create_element( 'tri6' )
# add to mesh using parameters (1st 3 points are at the same position as
# the geometric_points added above)
e_2_x = [ [14.0], [13.4], [6.0], [10.0], [13.0], [14.5] ]
e_2_y = [ [6.0], [10.3], [13.0], [15.0], [10.0], [5.0] ]
e_2_z = [ [-50.0], [-55.0], [-50.0], [-65.0], [-70.0], [-65.0] ]
gf.add_element_with_parameters( e_2, [e_2_x, e_2_y, e_2_z] )
gf.display_geometric_field( eval_density, field_glyph = 'sphere' )
| Python |
"""
FILE: scan_mesher.py
LAST MODIFIED: 25-Sept-2009
DESCRIPTION:
Class for creating a fieldwork mesh over a stack of images
"""
import scipy
import sys
sys.path.append( '../' )
from field import template_fields
from field.topology import element_types
class FemurMesher:
""" class for meshing femurs
"""
def __init__( self, scan, geometric_field ):
self.scan = scan
self.GF = geometric_field
self.shaft = None # shaft subvolume
#==================================================================#
def find_shaft( self, stdTol = 0.5 ):
""" locates the shaft of the femur and instantiate a subvolume
starting from the middle slice in the stack z direction
(shape[0]), examines every (spacing) slice and calculates the
radius stdev. If a slice's radius stdev exceeds tolerance from
the cumulative mean of previous slices, it is deemed either the
top or bottom of the shaft
"""
spacing = 2
slice0 = self.scan.I.shape[0]/2
sliceUp = slice0 - spacing
sliceDown = slice0 + spacing
done = 0
foundTop = 0
foundBottom = 0
meanStd = None
radiusStd = []
radiusMean = []
# do initial slice
slice = self.scan.createSubSlice( 0, slice0 )
sliceR = slice.calculateSlicePolar()[0]
radiusStd.append( sliceR.std() )
radiusMean.append( sliceR.mean() )
meanStd = scipy.mean( radiusStd )
while not done:
if ( not foundTop ) and ( sliceUp >= 0 ):
slice = self.scan.createSubSlice( 0, sliceUp )
sliceR = slice.calculateSlicePolar()[0]
if abs( sliceR.std() - meanStd ) > stdTol:
foundTop = 1
else:
radiusStd.insert( 0, sliceR.std() )
radiusMean.insert( 0, sliceR.mean() )
meanStd = scipy.mean( radiusStd )
sliceUp -= spacing
if ( not foundBottom ) and ( sliceDown <= (self.scan.I.shape[0] - 1) ):
slice = self.scan.createSubSlice( 0, sliceDown )
sliceR = slice.calculateSlicePolar()[0]
if abs( sliceR.std() - meanStd ) > stdTol:
foundBottom = 1
else:
radiusStd.append( sliceR.std() )
radiusMean.append( sliceR.mean() )
meanStd = scipy.mean( radiusStd )
sliceDown += spacing
if foundTop and foundBottom:
done = 1
# instantiate shaft subvolume
self.shaft = self.scan.createSubVolumes( 'shaft', [sliceUp, 0, 0], [sliceDown - sliceUp, self.scan.I.shape[1], self.scan.I.shape[2]] )
self.shaft_offset = [sliceUp, 0, 0]
print 'shaft slices:', [sliceUp, sliceDown]
return ( self.shaft, [sliceUp, sliceDown], radiusStd, radiusMean, meanStd )
#==================================================================#
def mesh_shaft( self, ring_n, ring_element_n):
""" generate stack of ring meshes for the shaft of a femur
"""
points_per_slice = ring_element_n * 2
points_per_ring = ring_element_n * 6
# get positions of geometric points
points = scipy.array( self._shaft_get_points( ring_n, ring_element_n ) )
#~ points = scipy.add( points, offset )
# create rings
for i in range( ring_n ):
# get the points for current ring
if i == 0:
ring_points = points[ 0 : points_per_ring ]
else:
ring_points = points[ i*points_per_ring - i*points_per_slice : (i+1)*points_per_ring - i*points_per_slice ]
#~ elif i == (ring_n - 1):
#~ ring_points = points[ i*points_per_ring - points_per_slice : ( i + 1 )*points_per_ring - points_per_slice ]
#~ else:
#~ ring_points = points[ i*points_per_ring - (i-1)*points_per_slice : (i+1)*points_per_ring - (i-1)*points_per_slice ]
#~
if not self._shaft_add_ring( ring_points, ring_element_n ):
print 'ERROR: FemurMesher.mesh_shaft: failed to add ring', i
print 'number of ring points:', len( ring_points )
print 'ring points:', ring_points
return
return 1
#==================================================================#
def _shaft_add_ring( self, points, ring_element_n ):
""" points = array([[x0,y0,z0],[x1,y1,z1],[...],...])
"""
ring = template_fields.two_quad_ring( ring_element_n )
parameters = []
for i in range( 3 ):
parameters.append( [ [v] for v in points[:,i] ] )
if self.GF.add_element_with_parameters( ring, parameters ):
return 1
else:
print 'ERROR: FemurMesher._shaft_add_ring: failed to add ring element'
return
#==================================================================#
def _shaft_get_points( self, ring_n, ring_element_n ):
""" find geometric points along the shaft of the femur
"""
slice_n = ring_n * 2 + 1 # number of slices
slice_points_n = ring_element_n * 2 # points per slice
slices = scipy.linspace( 0, self.shaft.I.shape[0]-1, slice_n ).round().astype( int ) # slice numbers
points = []
ridge_n = 0
#~ slice_point0s = [] # first point in each slice
for slice in slices:
s = self.shaft.createSubSlice( 0, slice )
# get points from this slice( 2D image )
slice_points = self._shaft_get_slice_points( s, slice_points_n, slice )
slice_points = scipy.add( slice_points, self.shaft_offset )
#~ slice_point0s.append( slice_points[0] )
for p in slice_points:
points.append( p )
# add 1st point in slice to geometric field as a landmark
self.GF.add_geometric_point( [ [v] for v in slice_points[0] ], name = 'shaft_ridge_'+str(ridge_n) )
ridge_n += 1
return points
#==================================================================#
def _shaft_get_slice_points( self, slice, nPoints, sliceN):
""" get_slice_points( slice, nPoints, sliceN ) -> list of
(x,y) for each point
slice is a 2D image array
centre: [x,y] position of the centre of the object
startV: [v1,v2] vector of the starting position from centre
nPoints: integer number of points to get
"""
points = []
averages = 10 # take position of closest 10 points
# starting angle
startV = slice.pAxes[ :, slice.pAxesMag.argmax() ]
theta0 = calcTheta( startV[0], startV[1] )
dtheta = 2*scipy.pi / nPoints
print startV
print theta0
# get all nonzero point indices
xi, yi = scipy.nonzero( slice.I )
# center
xi = xi - slice.CoM[0]
yi = yi - slice.CoM[1]
# get theta coords of all pixels in slice
theta = slice.calculateSlicePolar()[1]
for i in range( nPoints ):
# find closes data theta to t
t = theta0 + i*dtheta
if t > 2*scipy.pi:
t -= 2*scipy.pi
# get closest point indices
thetaDist = (theta - t)**2
tempPoints = []
for j in range( averages ):
closest_i = thetaDist.argmin()
thetaDist[ closest_i ] = scipy.inf
closest_c = [ xi[closest_i], yi[closest_i] ]
closest_c = [sliceN] + list( scipy.add( closest_c, slice.CoM ) )
tempPoints.append( closest_c )
# average
tempPoints = scipy.array( tempPoints )
points.append( tempPoints.mean( axis = 0 ) )
return points
#======================================================================#
def calcTheta( x, y ):
""" angle anticlockwise from the +ve x axis of a point (x,y)
"""
s = ( scipy.sign(x), scipy.sign(y) )
arct = scipy.arctan( y/x )
case = { (1, 1): arct,\
(-1, 1): scipy.pi + arct,\
(-1, -1): scipy.pi + arct,\
(1, -1): 2*scipy.pi + arct }
return case[s]
| Python |
#!/usr/bin/python
import sys
if __name__ == '__main__':
print 'this is called by myself'
else:
print 'import by other file'
def callHi():
print 'hi, I\'m called'
version = '0.1'
print 'done'
| Python |
#!/usr/bin/python
testList = ['111', '222', '333', '444'];
for item in testList:
print item,
print '\n'
testList.append("555");
for item in testList:
print item,
print '\n'
del testList[0];
print testList;
longTestList = [testList, 666]
print longTestList;
print longTestList[0][0];
print longTestList[0][1];
print longTestList[0][2];
raw = ('a', 'b', 'c');
longRaw = ('aa', 'bb', 'cc', raw);
print raw;
print longRaw;
print len(longRaw);
age = 22;
name = 'yinwu'
print 'my name is %s and age is %d' % (name, age);
print 'my name is %s and age is %s' % (name, age);
address = {
'a':'aaaaa',
'b':'bbbbb',
'c':'ccccc'
}
print address;
address['d'] = 'ddddd';
print address;
if address.has_key('a'):
print '%s have found with value %s' % ( 'a', address['a'] )
beforeCopy = 'test';
afterCopy = beforeCopy;
beforeCopy = 'testresult';
print beforeCopy,afterCopy;
testRaw = ['1','2','3','4','5'];
testRawCopy = testRaw;
del testRaw[0];
print testRaw;
print testRawCopy;
testString = 'WuYinkui'
if testString.startswith('Wu'):
print 'start ok';
if 'Yin' in testString:
print 'Yin is test string';
seperate = '/'
joinString = testRaw[0:2];
print seperate.join(joinString );
| Python |
#!/usr/bin/python
from Module import callHi, version
callHi()
print version
| Python |
#!/usr/bin/python
#import sys
a = 5
b = 6
del b;
print dir()
| Python |
#!/usr/bin/python
def getMax(a, b):
if a > b:
print a, 'is maxinum'
else:
print b, 'is maxinum'
a = 5
b = 6
c = 1000
d = 200000000000000000
def returnMax(a, b):
if a > b:
return a
else:
return b
print returnMax(a, b)
print returnMax(c, d)
#getMax(a, b)
#getMax(c, d)
print 'done'
| Python |
#!/usr/bin/python
testList = ['111', '222', '333', '444'];
for item in testList:
print item,
print '\n'
testList.append("555");
for item in testList:
print item,
print '\n'
del testList[0];
print testList;
longTestList = [testList, 666]
print longTestList;
print longTestList[0][0];
print longTestList[0][1];
print longTestList[0][2];
raw = ('a', 'b', 'c');
longRaw = ('aa', 'bb', 'cc', raw);
print raw;
print longRaw;
print len(longRaw);
age = 22;
name = 'yinwu'
print 'my name is %s and age is %d' % (name, age);
print 'my name is %s and age is %s' % (name, age);
address = {
'a':'aaaaa',
'b':'bbbbb',
'c':'ccccc'
}
print address;
address['d'] = 'ddddd';
print address;
if address.has_key('a'):
print '%s have found with value %s' % ( 'a', address['a'] )
beforeCopy = 'test';
afterCopy = beforeCopy;
beforeCopy = 'testresult';
print beforeCopy,afterCopy;
testRaw = ['1','2','3','4','5'];
testRawCopy = testRaw;
del testRaw[0];
print testRaw;
print testRawCopy;
testString = 'WuYinkui'
if testString.startswith('Wu'):
print 'start ok';
if 'Yin' in testString:
print 'Yin is test string';
seperate = '/'
joinString = testRaw[0:2];
print seperate.join(joinString );
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.