Skip to content
This repository has been archived by the owner on Jul 26, 2020. It is now read-only.

Commit

Permalink
Merge pull request #11 from scottsievert/pr/10
Browse files Browse the repository at this point in the history
Pull request 10 merge
  • Loading branch information
Scott S. committed Jul 24, 2015
2 parents 794c826 + 30a5ae4 commit 7c50f48
Show file tree
Hide file tree
Showing 22 changed files with 444 additions and 448 deletions.
2 changes: 2 additions & 0 deletions swix/swix.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,8 @@
D24A8549196D7D73009C18AC /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftMigration = 0700;
LastSwiftUpdateCheck = 0700;
LastUpgradeCheck = 0600;
ORGANIZATIONNAME = com.scott;
TargetAttributes = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,11 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "swix/tests.swift"
timestampString = "437169242.142289"
timestampString = "459378664.414002"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "341"
endingLineNumber = "341"
startingLineNumber = "340"
endingLineNumber = "340"
landmarkName = "functionTests()"
landmarkType = "5">
</BreakpointContent>
Expand All @@ -42,11 +42,11 @@
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "swix/main.swift"
timestampString = "430429795.929013"
timestampString = "459388981.990875"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "15"
endingLineNumber = "15">
startingLineNumber = "13"
endingLineNumber = "13">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
Expand Down
9 changes: 1 addition & 8 deletions swix/swix/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,5 @@
import Foundation
import Swift



runTests()
//SpeedTests()





//SpeedTests()
20 changes: 10 additions & 10 deletions swix/swix/speed.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ class SpeedTests {
}
}
func time(f:()->(), name:String="function"){
var start = NSDate()
let start = NSDate()
f()
println(NSString(format:"\(name) time (s): %.4f", -1 * start.timeIntervalSinceNow))
print(NSString(format:"\(name) time (s): %.4f", -1 * start.timeIntervalSinceNow))
}
func pe1(){
var N = 1e6
var x = arange(N)
let N = 1e6
let x = arange(N)
// seeing where that modulo is 0
var i = argwhere((abs(x%3) < 1e-9) || (abs(x%5) < 1e-9))
// println(sum(x[i]))
Expand All @@ -38,15 +38,15 @@ func pe10(){
var top = (sqrt(N.double)).int
for i in 2 ..< top{
var max:Int = (N/i)
var j = arange(2, max.double) * i.double
var j = arange(2, max: max.double) * i.double
primes[j] *= 0.0
}
// sum(primes) is the correct answer
}
func pe73(){
var N = 1e3
var i = arange(N)+1
var (n, d) = meshgrid(i, i)
var (n, d) = meshgrid(i, y: i)

var f = (n / d).flat
f = unique(f)
Expand All @@ -57,9 +57,9 @@ func pe73(){

func soft_thresholding(){
let N = 1e2.int
var j = linspace(-1, 1, num:N)
var (x, y) = meshgrid(j, j)
var z = pow(x, 2) + pow(y, 2)
var j = linspace(-1, max: 1, num:N)
var (x, y) = meshgrid(j, y: j)
var z = pow(x, power: 2) + pow(y, power: 2)
var i = abs(z) < 0.5
z[argwhere(i)] *= 0
z[argwhere(1-i)] -= 0.5
Expand All @@ -68,7 +68,7 @@ func soft_thresholding(){


func pi_approx(){
var N = 1e6
let N = 1e6
var k = arange(N)
var pi_approx = 1 / (2*k + 1)
pi_approx[2*k[0..<(N/2).int]+1] *= -1
Expand Down
65 changes: 37 additions & 28 deletions swix/swix/swix/io.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,37 +9,36 @@
import Foundation

// ndarray binary
func write_binary(x:ndarray, #filename:String, prefix:String=S2_PREFIX){
var N = x.n
var data = NSData(bytes:!x, length:N*sizeof(Double))
func write_binary(x:ndarray, filename:String, prefix:String=S2_PREFIX){
let N = x.n
let data = NSData(bytes:!x, length:N*sizeof(Double))
data.writeToFile(prefix+"../"+filename, atomically: false)
}
func read_binary(filename:String, prefix:String=S2_PREFIX) -> ndarray{
var read = NSData(contentsOfFile: prefix+"../"+filename)
var l:Int! = read?.length
var sD:Int = sizeof(Double)
var count = (l.double / sD.double)
let read = NSData(contentsOfFile: prefix+"../"+filename)
let l:Int! = read?.length
let sD:Int = sizeof(Double)
let count = (l.double / sD.double)

var y = zeros(count.int)
let y = zeros(count.int)
read?.getBytes(!y, length: count.int*sizeof(Double))
return y
}

// matrix binary
func write_binary(x:matrix, #filename:String, prefix:String=S2_PREFIX){
var y = concat(array(x.shape.0.double, x.shape.1.double), x.flat)
func write_binary(x:matrix, filename:String, prefix:String=S2_PREFIX){
let y = concat(array(x.shape.0.double, x.shape.1.double), y: x.flat)
write_binary(y, filename:filename, prefix:prefix)
}
func read_binary(filename:String, prefix:String=S2_PREFIX)->matrix{
var a:ndarray = read_binary(filename, prefix:prefix)
var (w, h) = (a[0], a[1])
var b = reshape(a[2..<a.n], (w.int,h.int))
return b
let (w, h) = (a[0], a[1])
return reshape(a[2..<a.n], shape: (w.int,h.int))
}


// ndarray csv
func write_csv(x:ndarray, #filename:String, prefix:String=S2_PREFIX){
func write_csv(x:ndarray, filename:String, prefix:String=S2_PREFIX){
// write the array to CSV
var seperator=","
var str = ""
Expand All @@ -48,21 +47,26 @@ func write_csv(x:ndarray, #filename:String, prefix:String=S2_PREFIX){
str += String(format: "\(x[i])"+seperator)
}
str += "\n"
var error:NSError?
str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding, error: &error)
if let error=error{
println("File probably wasn't recognized \n\(error)")
do {
try str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding)
} catch {
Swift.print("File probably wasn't recognized")
}

}
func read_csv(filename:String, prefix:String=S2_PREFIX) -> ndarray{
var x = String(contentsOfFile: prefix+"../"+filename, encoding: NSUTF8StringEncoding, error: nil)
var x: String?
do {
x = try String(contentsOfFile: prefix+"../"+filename, encoding: NSUTF8StringEncoding)
} catch _ {
x = nil
}
var array:[Double] = []
var columns:Int = 0
var z = x!.componentsSeparatedByString(",")
columns = 0
for i in 0..<z.count{
var num = z[i]
let num = z[i]
array.append(num.doubleValue)
columns += 1
}
Expand All @@ -73,13 +77,18 @@ func read_csv(filename:String, prefix:String=S2_PREFIX) -> ndarray{

// matrix csv
func read_csv(filename:String, prefix:String=S2_PREFIX) -> matrix{
var x = String(contentsOfFile: prefix+"../"+filename, encoding: NSUTF8StringEncoding, error: nil)
var x: String?
do {
x = try String(contentsOfFile: prefix+"../"+filename, encoding: NSUTF8StringEncoding)
} catch _ {
x = nil
}
var y = x!.componentsSeparatedByString("\n")
var rows = y.count-1
let rows = y.count-1
var array:[Double] = []
var columns:Int = 0
for i in 0..<rows{
var z = y[i].componentsSeparatedByString(",")
let z = y[i].componentsSeparatedByString(",")
columns = 0
for num in z{
array.append(num.doubleValue)
Expand All @@ -90,7 +99,7 @@ func read_csv(filename:String, prefix:String=S2_PREFIX) -> matrix{
done.flat.grid = array
return done
}
func write_csv(x:matrix, #filename:String, prefix:String=S2_PREFIX){
func write_csv(x:matrix, filename:String, prefix:String=S2_PREFIX){
var seperator=","
var str = ""
for i in 0..<x.shape.0{
Expand All @@ -100,10 +109,10 @@ func write_csv(x:matrix, #filename:String, prefix:String=S2_PREFIX){
}
str += "\n"
}
var error:NSError?
str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding, error: &error)
if let error=error{
println("File probably wasn't recognized \n\(error)")
do {
try str.writeToFile(prefix+"../"+filename, atomically: false, encoding: NSUTF8StringEncoding)
} catch {
Swift.print("File probably wasn't recognized")
}
}

Expand Down
8 changes: 4 additions & 4 deletions swix/swix/swix/machine_learning/machine_learning.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ class SVM {
// svm_type: C_SVC, ONE_CLASS, NU_SVC, NU_SVR

// careful: NU_SVR and SIGMOID throws an exception error
self.cvsvm.setParams(svm_type.nsstring, kernel:kernel_type.nsstring, nu:nu.cfloat)
self.cvsvm.setParams(svm_type.nsstring as String, kernel:kernel_type.nsstring as String, nu:nu.cfloat)
}
func train(responses: matrix, _ targets: ndarray){
// convert matrix2d to NSArray
Expand All @@ -42,11 +42,11 @@ class SVM {
}
func predict(response: ndarray) -> Double{
assert(self.N == response.count, "Sizes of input arguments do not match: predict.count != trained.count. The varianbles you're trying to predict a result from must match variables you trained off of.")
var tp = self.cvsvm.predict(!response, n:self.N.cint)
let tp = self.cvsvm.predict(!response, n:self.N.cint)
return tp.double
}
func predict(responses: matrix) -> ndarray{
var y = zeros(responses.shape.0)
let y = zeros(responses.shape.0)
assert(self.N == responses.shape.1, "Sizes must match")
self.cvsvm.predict(!responses, into:!y, m:responses.shape.0.cint, n:responses.shape.1.cint);
return y
Expand Down Expand Up @@ -75,7 +75,7 @@ class kNearestNeighbors{
func predict(x: ndarray, k: Int) -> Double{
assert(self.N == x.count, "Sizes of input arguments do not match: predict.count != trained.count. The varianbles you're trying to predict a result from must match variables you trained off of.")
assert(k <= 32, "k <= 32 for performance reasons enforced by OpenCV.")
var result = self.knn.predict(!x, n:x.n.cint, k:k.cint)
let result = self.knn.predict(!x, n:x.n.cint, k:k.cint)
return result.double;
}
}
Expand Down
59 changes: 28 additions & 31 deletions swix/swix/swix/matrix/m-complex-math.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ import Swift
import Accelerate

func rank(x:matrix)->Double{
var (u, S, v) = svd(x, compute_uv:false)
var m:Double = (x.shape.0 < x.shape.1 ? x.shape.1 : x.shape.0).double
var tol = S.max() * m * DOUBLE_EPSILON
let (_, S, _) = svd(x, compute_uv:false)
let m:Double = (x.shape.0 < x.shape.1 ? x.shape.1 : x.shape.0).double
let tol = S.max() * m * DOUBLE_EPSILON
return sum(S > tol)
}
func dot(x: matrix, y: matrix) -> matrix{
var (Mx, Nx) = x.shape
var (My, Ny) = y.shape
let (Mx, Nx) = x.shape
let (My, Ny) = y.shape
assert(Nx == My, "Matrix sizes not compatible for dot product")
var z = zeros((Mx, Ny))
let z = zeros((Mx, Ny))
cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasNoTrans,
Mx.cint, Ny.cint, Nx.cint, 1.0,
!x, Nx.cint,
Expand All @@ -29,44 +29,44 @@ func dot(x: matrix, y: matrix) -> matrix{
return z
}
func svd(x: matrix, compute_uv:Bool=true) -> (matrix, ndarray, matrix){
var (m, n) = x.shape
var nS = m < n ? m : n // number singular values
var sigma = zeros(nS)
var vt = zeros((n,n))
let (m, n) = x.shape
let nS = m < n ? m : n // number singular values
let sigma = zeros(nS)
let vt = zeros((n,n))
var u = zeros((m,m))

var xx = zeros_like(x)
xx.flat = x.flat
xx = xx.T
var c_uv:CInt = compute_uv==true ? 1 : 0
let c_uv:CInt = compute_uv==true ? 1 : 0
svd_objc(!xx, m.cint, n.cint, !sigma, !vt, !u, c_uv)

// to get the svd result to match Python
var v = transpose(vt)
let v = transpose(vt)
u = transpose(u)

return (u, sigma, v)
}
func pinv(x:matrix)->matrix{
var (u, s, v) = svd(x)
var m = u.shape.0
var n = v.shape.1
var ma = m < n ? n : m
var cutoff = DOUBLE_EPSILON * ma.double * max(s)
var i = s > cutoff
var ipos = argwhere(i)
let m = u.shape.0
let n = v.shape.1
let ma = m < n ? n : m
let cutoff = DOUBLE_EPSILON * ma.double * max(s)
let i = s > cutoff
let ipos = argwhere(i)
s[ipos] = 1 / s[ipos]
var ineg = argwhere(1-i)
let ineg = argwhere(1-i)
s[ineg] = zeros_like(ineg)
var z = zeros((n, m))
z["diag"] = s
var res = v.T.dot(z).dot(u.T)
let res = v.T.dot(z).dot(u.T)
return res
}
func inv(x: matrix) -> matrix{
assert(x.shape.0 == x.shape.1, "To take an inverse of a matrix, the matrix must be square. If you want the inverse of a rectangular matrix, use psuedoinverse.")
var y = x.copy()
var (M, N) = x.shape
let y = x.copy()
let (M, N) = x.shape

var ipiv:Array<__CLPK_integer> = Array(count:M*M, repeatedValue:0)
var lwork:__CLPK_integer = __CLPK_integer(N*N)
Expand All @@ -79,31 +79,28 @@ func inv(x: matrix) -> matrix{
return y
}
func solve(A: matrix, b: ndarray) -> ndarray{
var (m, n) = A.shape
let (m, n) = A.shape
assert(b.n == m, "Ax = b, A.rows == b.n. Sizes must match which makes sense mathematically")
assert(n == m, "Matrix must be square -- dictated by OpenCV")
var x = zeros(n)
let x = zeros(n)
CVWrapper.solve(!A, b:!b, x:!x, m:m.cint, n:n.cint)
return x
}
func eig(x: matrix)->ndarray{
// matrix, value, vectors
var (m, n) = x.shape
let (m, n) = x.shape
assert(m == n, "Input must be square")

var value_real = zeros(m)
var value_imag = zeros(n)
let value_real = zeros(m)
let value_imag = zeros(n)
var vector = zeros((n,n))

var y = x.copy()

var work:[Double] = Array(count:n*n, repeatedValue:0.0)
var lwork = __CLPK_integer(4 * n)
var info = __CLPK_integer(1)

// don't compute right or left eigenvectors
var job = "N"
var ccharOptional = job.cStringUsingEncoding(NSUTF8StringEncoding)?[0] // CChar?
let job = "N"
var jobvl = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!
var jobvr = (job.cStringUsingEncoding(NSUTF8StringEncoding)?[0])!

Expand Down
Loading

0 comments on commit 7c50f48

Please sign in to comment.