import UIKit
import SceneKit
import PlaygroundSupport
// Constants
let c: Double = 299792.458 // speed of light in km/s
let H0: Double = 70 // Hubble constant in km/s/Mpc
let G: Double = 6.6743e-11 // gravitational constant in m^3/kg/s^2
let rho_crit: Double = 1.878e-26 // critical density of the universe in kg/m^3
// Parameters
let N: Int = 1000 // number of particles
let t0: Double = 0 // initial time in Gyr
let tf: Double = 13.8 // final time in Gyr
let dt: Double = 0.01 // time step in Gyr
let a0: Double = 1 / (1 + t0 * H0 / 2997.92) // initial scale factor
// Generate initial conditions
let x = (0..<N).map { _ in
return SCNVector3(
CGFloat(Double.random(in: -10...10)),
CGFloat(Double.random(in: -10...10)),
CGFloat(Double.random(in: -10...10))
)
}
let v = (0..<N).map { _ in
return SCNVector3(
CGFloat(Double.random(in: -100...100)),
CGFloat(Double.random(in: -100...100)),
CGFloat(Double.random(in: -100...100))
)
}
let m = (0..<N).map { _ in
return CGFloat(Double.random(in: 1e11...2e11))
}
// Define Friedmann equations
func HubbleParameter(_ a: Double) -> Double {
return H0 * sqrt((rho_crit / 3) * (1 / pow(a, 3)))
}
func Acceleration(_ x: SCNVector3, _ v: SCNVector3) -> SCNVector3 {
let r = x.length()
let a = SCNVector3(
-G * x.x / pow(r, 3),
-G * x.y / pow(r, 3),
-G * x.z / pow(r, 3)
) * m.reduce(0, +)
a -= SCNVector3(
Float(HubbleParameter(1) * Double(x.x)),
Float(HubbleParameter(1) * Double(x.y)),
Float(HubbleParameter(1) * Double(x.z))
)
return a
}
// Initialize arrays for storing data
let t = stride(from: t0, to: tf, by: dt).map { $0 }
var a = Array(repeating: 0.0, count: t.count)
var v = Array(repeating: SCNVector3Zero, count: t.count)
var x = Array(repeating: SCNVector3Zero, count: t.count)
// Set initial conditions
a[0] = a0
v[0] = v[0]
x[0] = x[0]
// Integrate equations of motion using Verlet algorithm
for i in 1..<t.count {
x[i] = x[i-1] + v[i-1] * Float(dt) + Acceleration(x[i-1], v[i-1]) * pow(Float(dt), 2) / 2
a[i] = a0 * (1 + HubbleParameter(a0) * (t[i] - t0)) // scale factor as a function of time
v[i] = v[i-1]
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
import UIKit
import SceneKit
import PlaygroundSupport
class BatteryDesignGenerator {
// ... (previous code for design generation and optimization)
}
class SolidStateLithiumBatteryAnimator {
var batteryName: String
var blueprintData: [[SCNNode]]
var sceneView: SCNView
init(batteryName: String, blueprintData: [[SCNNode]]) {
self.batteryName = batteryName
self.blueprintData = blueprintData
// Create a scene view to display the 3D animation
self.sceneView = SCNView(frame: CGRect(x: 0, y: 0, width: 600, height: 400))
self.sceneView.backgroundColor = UIColor.white
self.sceneView.autoenablesDefaultLighting = true
self.sceneView.allowsCameraControl = true
self.sceneView.scene = SCNScene()
// Add the scene view to the playground live view
PlaygroundPage.current.liveView = sceneView
}
func animate() {
// Create a parent node to hold all the components
let parentNode = SCNNode()
// Add the blueprint components to the parent node
for row in blueprintData {
for component in row {
parentNode.addChildNode(component)
}
}
// Add the parent node to the scene
sceneView.scene?.rootNode.addChildNode(parentNode)
// Animate the parent node
let rotationAction = SCNAction.rotateBy(x: 0, y: 2 * .pi, z: 0, duration: 10)
let repeatAction = SCNAction.repeatForever(rotationAction)
parentNode.runAction(repeatAction)
}
}
// Battery design generation and optimization
let generator = BatteryDesignGenerator()
let bestDesign = generator.optimizeDesign()
// Animation of the 3D representation
let batteryName = "RevolutionY"
let animator = SolidStateLithiumBatteryAnimator(batteryName: batteryName, blueprintData: bestDesign)
animator.animate()
I have a few swift codes to share that others may want I was trying to compile swift playgrounds programs on my iPhone I am interested in making an App for it possibly it has been a long time since I used a MAC
First Code…Swift Compiler
import subprocess
def compile_swift_code(code):
try:
# Write the Swift code to a temporary file
with open('temp.swift', 'w') as file:
file.write(code)
# Compile the Swift code using the subprocess module
subprocess.run(['swiftc', '-o', 'output', 'temp.swift'], check=True)
# Execute the compiled program and capture the output
completed_process = subprocess.run(['./output'], capture_output=True, text=True)
output = completed_process.stdout
return output.strip()
except subprocess.CalledProcessError as e:
print("Compilation error:", e)
return None
Example usage
swift_code = '''
print("Hello, world!")
'''
output = compile_swift_code(swift_code)
if output is not None:
print(output)
Second Code
example program that simulates the expansion of the universe from the Big Bang to the present day using N-body simulations and the Friedmann equations in swift playgrounds code
import UIKit
import SceneKit
import PlaygroundSupport
import simd
// Constants
let c: Double = 299792.458 // speed of light in km/s
let H0: Double = 70 // Hubble constant in km/s/Mpc
let G: Double = 6.6743e-11 // gravitational constant in m^3/kg/s^2
let rho_crit: Double = 1.878e-26 // critical density of the universe in kg/m^3
// Parameters
let N: Int = 1000 // number of particles
let t0: Double = 0 // initial time in Gyr
let tf: Double = 13.8 // final time in Gyr
let dt: Double = 0.01 // time step in Gyr
let a0: Double = 1 / (1 + t0 * H0 / 2997.92) // initial scale factor
// Generate initial conditions
var x = (0..<N).map { _ in return simd_double3(Double.random(in: -10..<10), Double.random(in: -10..<10), Double.random(in: -10..<10)) }
var v = (0..<N).map { _ in return simd_double3(Double.random(in: -100..<100), Double.random(in: -100..<100), Double.random(in: -100..<100)) }
var m = (0..<N).map { _ in return Double.random(in: 1e11..<1.1e11) }
// Define Friedmann equations
func HubbleParameter(a: Double) -> Double {
return H0 * sqrt((rho_crit / 3) * (1 / pow(a, 3)))
}
func Acceleration(x: [simd_double3], v: [simd_double3]) -> [simd_double3] {
let r = x.map { return length($0) }
var a = [simd_double3](repeating: simd_double3(0), count: N)
for i in 0..<N {
a[i] = -G * (x[i] / pow(r[i], 3)) * m
a[i] -= HubbleParameter(a: 1) * x[i]
}
return a
}
// Initialize arrays for storing data
var t = stride(from: t0, to: tf, by: dt).map { return $0 }
var a = [Double](repeating: 0, count: t.count)
var v = [simd_double3](repeating: simd_double3(0), count: N)
var x = [simd_double3](repeating: simd_double3(0), count: N)
// Set initial conditions
a[0] = a0
v[0] = v[0]
x[0] = x[0]
// Integrate equations of motion using Verlet algorithm
for i in 1..<t.count {
x[i] = x[i-1] + v[i-1] * dt + 0.5 * Acceleration(x: x, v: v)[i-1] * dt * dt
a[i] = a0 * (1 + HubbleParameter(a: a0) * (t[i] - t0)) // scale factor as a function of time
v[i] = v[i-1] + 0.5 * (Acceleration(x: x, v: v)[i] + Acceleration(x: x, v: v)[i-1]) * dt
}
// Plot results
I have a few more codes and some new engine/motor designs
import UIKit
import SceneKit
import PlaygroundSupport
// Constants
let c: Double = 299792.458 // speed of light in km/s
let H0: Double = 70 // Hubble constant in km/s/Mpc
let G: Double = 6.6743e-11 // gravitational constant in m^3/kg/s^2
let rho_crit: Double = 1.878e-26 // critical density of the universe in kg/m^3
// Parameters
let N: Int = 1000 // number of particles
let t0: Double = 0 // initial time in Gyr
let tf: Double = 13.8 // final time in Gyr
let dt: Double = 0.01 // time step in Gyr
let a0: Double = 1 / (1 + t0 * H0 / 2997.92) // initial scale factor
// Generate initial conditions
let x = (0..<N).map { _ in
return SCNVector3(
CGFloat(Double.random(in: -10...10)),
CGFloat(Double.random(in: -10...10)),
CGFloat(Double.random(in: -10...10))
)
}
let v = (0..<N).map { _ in
return SCNVector3(
CGFloat(Double.random(in: -100...100)),
CGFloat(Double.random(in: -100...100)),
CGFloat(Double.random(in: -100...100))
)
}
let m = (0..<N).map { _ in
return CGFloat(Double.random(in: 1e11...2e11))
}
// Define Friedmann equations
func HubbleParameter(_ a: Double) -> Double {
return H0 * sqrt((rho_crit / 3) * (1 / pow(a, 3)))
}
func Acceleration(_ x: SCNVector3, _ v: SCNVector3) -> SCNVector3 {
let r = x.length()
let a = SCNVector3(
-G * x.x / pow(r, 3),
-G * x.y / pow(r, 3),
-G * x.z / pow(r, 3)
) * m.reduce(0, +)
a -= SCNVector3(
Float(HubbleParameter(1) * Double(x.x)),
Float(HubbleParameter(1) * Double(x.y)),
Float(HubbleParameter(1) * Double(x.z))
)
return a
}
// Plasma Electric Motor
class PlasmaElectricMotor {
let plasmaDensity: Double
let magneticFieldStrength: Double
init(plasmaDensity: Double, magneticFieldStrength: Double) {
self.plasmaDensity = plasmaDensity
self.magneticFieldStrength = magneticFieldStrength
}
func calculateThrust() -> Double {
// Constants
let ionCharge: Double = 1.6e-19 // Coulombs
let plasmaSpeed: Double = 1e5 // m/s
// Calculate the thrust
let thrust = 0.5 * plasmaDensity * pow(plasmaSpeed, 2) * ionCharge * magneticFieldStrength
return thrust
}
func calculatePower() -> Double {
// Constants
let plasmaCrossSection: Double = Double.pi * pow(0.1, 2) // m^2
let plasmaSpeed: Double = 1e5 // m/s
let ionCharge: Double =
import UIKit
import PlaygroundSupport
class BlueprintView: UIView {
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else { return }
// Set up drawing parameters
context.setLineWidth(2)
context.setStrokeColor(UIColor.black.cgColor)
// Draw the motor body
let bodyRect = CGRect(x: 100, y: 100, width: 200, height: 300)
context.stroke(bodyRect)
// Draw the plasma density input
let plasmaDensityRect = CGRect(x: 100, y: 50, width: 50, height: 30)
context.stroke(plasmaDensityRect)
// Draw the magnetic field strength input
let magneticFieldRect = CGRect(x: 250, y: 50, width: 50, height: 30)
context.stroke(magneticFieldRect)
// Draw the power output
let powerRect = CGRect(x: 100, y: 420, width: 50, height: 30)
context.stroke(powerRect)
// Draw the thrust output
let thrustRect = CGRect(x: 250, y: 420, width: 50, height: 30)
context.stroke(thrustRect)
// Add labels
let attributes: [NSAttributedString.Key: Any] = [
.font: UIFont.systemFont(ofSize: 14),
.foregroundColor: UIColor.black
]
let densityLabel = NSAttributedString(string: "Plasma Density", attributes: attributes)
densityLabel.draw(at: CGPoint(x: 100, y: 20))
let magneticFieldLabel = NSAttributedString(string: "Magnetic Field", attributes: attributes)
magneticFieldLabel.draw(at: CGPoint(x: 250, y: 20))
let powerLabel = NSAttributedString(string: "Power Output", attributes: attributes)
powerLabel.draw(at: CGPoint(x: 100, y: 390))
let thrustLabel = NSAttributedString(string: "Thrust Output", attributes: attributes)
thrustLabel.draw(at: CGPoint(x: 250, y: 390))
}
}
let blueprintView = BlueprintView(frame: CGRect(x: 0, y: 0, width: 400, height: 500))
blueprintView.backgroundColor = UIColor.white
PlaygroundPage.current.liveView = blueprintView
import UIKit
import SceneKit
import PlaygroundSupport
class BlueprintScene: SCNScene {
override init() {
super.init()
// Create motor body node
let motorBodyGeometry = SCNBox(width: 2, height: 3, length: 4, chamferRadius: 0.1)
let motorBodyNode = SCNNode(geometry: motorBodyGeometry)
motorBodyNode.position = SCNVector3(0, 0, 0)
rootNode.addChildNode(motorBodyNode)
// Create plasma density input node
let plasmaDensityGeometry = SCNBox(width: 0.5, height: 0.3, length: 0.2, chamferRadius: 0.05)
let plasmaDensityNode = SCNNode(geometry: plasmaDensityGeometry)
plasmaDensityNode.position = SCNVector3(-1, 1, 0)
rootNode.addChildNode(plasmaDensityNode)
// Create magnetic field strength input node
let magneticFieldGeometry = SCNBox(width: 0.5, height: 0.3, length: 0.2, chamferRadius: 0.05)
let magneticFieldNode = SCNNode(geometry: magneticFieldGeometry)
magneticFieldNode.position = SCNVector3(1, 1, 0)
rootNode.addChildNode(magneticFieldNode)
// Create power output node
let powerGeometry = SCNBox(width: 0.5, height: 0.3, length: 0.2, chamferRadius: 0.05)
let powerNode = SCNNode(geometry: powerGeometry)
powerNode.position = SCNVector3(-1, -1, 0)
rootNode.addChildNode(powerNode)
// Create thrust output node
let thrustGeometry = SCNBox(width: 0.5, height: 0.3, length: 0.2, chamferRadius: 0.05)
let thrustNode = SCNNode(geometry: thrustGeometry)
thrustNode.position = SCNVector3(1, -1, 0)
rootNode.addChildNode(thrustNode)
// Add labels
let labelFont = UIFont.systemFont(ofSize: 0.2)
let densityLabel = createLabelNode(text: "Plasma Density", font: labelFont)
densityLabel.position = SCNVector3(-1, 1.4, 0)
rootNode.addChildNode(densityLabel)
let magneticFieldLabel = createLabelNode(text: "Magnetic Field", font: labelFont)
magneticFieldLabel.position = SCNVector3(1, 1.4, 0)
rootNode.addChildNode(magneticFieldLabel)
let powerLabel = createLabelNode(text: "Power Output", font: labelFont)
powerLabel.position = SCNVector3(-1, -1.4, 0)
rootNode.addChildNode(powerLabel)
let thrustLabel = createLabelNode(text: "Thrust Output", font: labelFont)
thrustLabel.position = SCNVector3(1, -1.4, 0)
rootNode.addChildNode(thrustLabel)
// Set up camera
let cameraNode = SCNNode()
cameraNode.camera = SCNCamera()
cameraNode.position = SCNVector3(0, 0, 8)
rootNode.addChildNode(cameraNode)
// Set up lighting
let ambientLightNode = SCNNode()
ambientLightNode.light = SCNLight