<commit_before>//
//  GraphViewController.swift
//  Swift-AI-iOS
//
//  Created by <NAME> on 11/22/15.
//

import UIKit
import APKit

class GraphViewController: UIViewController {
    
    let graphView = GraphView()
    /// The number of points to plot on screen
    var numPoints = 0
    /// Array of all points to display in the graph
    var points = [CALayer]()
    /// Our neural network
    private var network = FFNN(inputs: 1, hidden: 8, outputs: 1, learningRate: 0.6, momentum: 0.8, weights: nil, activationFunction: .Sigmoid, errorFunction: .Default(average: false))
    /// Serial queue for synchronizing access to neural network from multiple threads
    private let networkQueue = dispatch_queue_create("com.SwiftAI.networkQueue", DISPATCH_QUEUE_SERIAL)
    /// A multiplier, for altering the target function
    private var functionMultiplier: Float = 1.5
    /// State variable to start/stop the network's training when needed
    private var paused = true
    /// State variable to resume trainig after a reset, if needed
    private var toContinue = false
    
    override func loadView() {
        self.view = self.graphView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure buttons
        self.graphView.startPauseButton.addTarget(self, action: "startPause", forControlEvents: .TouchUpInside)
        self.graphView.infoButton.addTarget(self, action: "infoTapped", forControlEvents: .TouchUpInside)
        self.graphView.resetButton.addTarget(self, action: "resetAll", forControlEvents: .TouchUpInside)
        // Configure slider for multiplier
        self.graphView.slider.addTarget(self, action: "sliderMoved:", forControlEvents: .ValueChanged)
        // Set function label text
        self.graphView.functionLabel.setTitle("y = sin (\(self.functionMultiplier)x)", forState: .Normal)
        // Calculate number of points to plot, based on screen size (#hack)
        self.numPoints = Int((UIScreen.mainScreen().bounds.width - 20))// / 2) // -20 for margins
    }
    
    override func viewDidAppear(animated: Bool) {
        // Happens here so we have a frame for our CGContext to draw curves
        self.resetAll()
    }
    
    override func viewWillDisappear(animated: Bool) {
        self.graphView.startPauseButton.setImage(UIImage(named: "play"), forState: .Normal)
        self.graphView.startPauseButton.setImage(UIImage(named: "play_highlighted"), forState: .Highlighted)
        self.graphView.startPauseButton.backgroundColor = UIColor.swiftGreen()
        self.pauseTraining()
    }
    
    func startPause() {
        switch self.paused {
        case true:
            self.graphView.startPauseButton.setImage(UIImage(named: "pause"), forState: .Normal)
            self.graphView.startPauseButton.setImage(UIImage(named: "pause_highlighted"), forState: .Highlighted)
            self.graphView.startPauseButton.backgroundColor = UIColor.swiftDarkOrange()
            self.startTraining()
        case false:
            self.graphView.startPauseButton.setImage(UIImage(named: "play"), forState: .Normal)
            self.graphView.startPauseButton.setImage(UIImage(named: "play_highlighted"), forState: .Highlighted)
            self.graphView.startPauseButton.backgroundColor = UIColor.swiftGreen()
            self.pauseTraining()
        }
    }
    
    func sliderMoved(sender: UISlider) {
        self.functionMultiplier = sender.value
        let constantString = Double(self.functionMultiplier).toString(decimalPlaces: 1)
        self.graphView.functionLabel.setTitle("y = sin (" + constantString + "x)", forState: .Normal)
        self.updateTarget()
    }
    
    func startTraining() {
        self.paused = false
        // Dispatches training process to background thread
        dispatch_async(self.networkQueue) {
            var epoch = 0
            while !self.paused {
                for index in 0..<self.numPoints {
                    let x = (-500 + (Float(index) * 1000) / Float(self.numPoints)) / 100
                    try! self.network.update(inputs: [x])
                    let answer = self.sineFunc(x)
                    try! self.network.backpropagate(answer: [answer])
                }
                if epoch % 10 == 0 {
                    let ys = self.computePoints()
                    dispatch_async(dispatch_get_main_queue()) {
                        self.updatePoints(ys)
                    }
                }
                ++epoch
            }
        }
    }
    
    /// Returns new y coordinates for each point from the network
    /// This func must be called on self.networkQueue
    func computePoints() -> [Float] {
        return (0..<self.numPoints).map { index -> Float in
            let x = (-500 + (Float(index) * 1000) / Float(self.numPoints)) / 100
            return try! self.network.update(inputs: [x]).first!
        }
    }
    
    /// Updates the points on screen with the given y coordinates.
    /// This func must be called on the main queue
    func updatePoints(ys: [Float]) {
        for index in 0..<self.numPoints {
            let y = ys[index]
            self.updatePoint(index, y: CGFloat(y * -250) + 125)
        }
    }
    
    func pauseTraining() {<commit_msg>Keep graphics-related constants together<commit_after>//
//  GraphViewController.swift
//  Swift-AI-iOS
//
//  Created by <NAME> on 11/22/15.
//

import UIKit
import APKit

class GraphViewController: UIViewController {
    
    let graphView = GraphView()
    /// The number of points to plot on screen
    var numPoints = 0
    /// Array of all points to display in the graph
    var points = [CALayer]()
    /// Our neural network
    private var network = FFNN(inputs: 1, hidden: 8, outputs: 1, learningRate: 0.6, momentum: 0.8, weights: nil, activationFunction: .Sigmoid, errorFunction: .Default(average: false))
    /// Serial queue for synchronizing access to neural network from multiple threads
    private let networkQueue = dispatch_queue_create("com.SwiftAI.networkQueue", DISPATCH_QUEUE_SERIAL)
    /// A multiplier, for altering the target function
    private var functionMultiplier: Float = 1.5
    /// State variable to start/stop the network's training when needed
    private var paused = true
    /// State variable to resume trainig after a reset, if needed
    private var toContinue = false
    
    override func loadView() {
        self.view = self.graphView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure buttons
        self.graphView.startPauseButton.addTarget(self, action: "startPause", forControlEvents: .TouchUpInside)
        self.graphView.infoButton.addTarget(self, action: "infoTapped", forControlEvents: .TouchUpInside)
        self.graphView.resetButton.addTarget(self, action: "resetAll", forControlEvents: .TouchUpInside)
        // Configure slider for multiplier
        self.graphView.slider.addTarget(self, action: "sliderMoved:", forControlEvents: .ValueChanged)
        // Set function label text
        self.graphView.functionLabel.setTitle("y = sin (\(self.functionMultiplier)x)", forState: .Normal)
        // Calculate number of points to plot, based on screen size (#hack)
        self.numPoints = Int((UIScreen.mainScreen().bounds.width - 20))// / 2) // -20 for margins
    }
    
    override func viewDidAppear(animated: Bool) {
        // Happens here so we have a frame for our CGContext to draw curves
        self.resetAll()
    }
    
    override func viewWillDisappear(animated: Bool) {
        self.graphView.startPauseButton.setImage(UIImage(named: "play"), forState: .Normal)
        self.graphView.startPauseButton.setImage(UIImage(named: "play_highlighted"), forState: .Highlighted)
        self.graphView.startPauseButton.backgroundColor = UIColor.swiftGreen()
        self.pauseTraining()
    }
    
    func startPause() {
        switch self.paused {
        case true:
            self.graphView.startPauseButton.setImage(UIImage(named: "pause"), forState: .Normal)
            self.graphView.startPauseButton.setImage(UIImage(named: "pause_highlighted"), forState: .Highlighted)
            self.graphView.startPauseButton.backgroundColor = UIColor.swiftDarkOrange()
            self.startTraining()
        case false:
            self.graphView.startPauseButton.setImage(UIImage(named: "play"), forState: .Normal)
            self.graphView.startPauseButton.setImage(UIImage(named: "play_highlighted"), forState: .Highlighted)
            self.graphView.startPauseButton.backgroundColor = UIColor.swiftGreen()
            self.pauseTraining()
        }
    }
    
    func sliderMoved(sender: UISlider) {
        self.functionMultiplier = sender.value
        let constantString = Double(self.functionMultiplier).toString(decimalPlaces: 1)
        self.graphView.functionLabel.setTitle("y = sin (" + constantString + "x)", forState: .Normal)
        self.updateTarget()
    }
    
    func startTraining() {
        self.paused = false
        // Dispatches training process to background thread
        dispatch_async(self.networkQueue) {
            var epoch = 0
            while !self.paused {
                for index in 0..<self.numPoints {
                    let x = (-500 + (Float(index) * 1000) / Float(self.numPoints)) / 100
                    try! self.network.update(inputs: [x])
                    let answer = self.sineFunc(x)
                    try! self.network.backpropagate(answer: [answer])
                }
                if epoch % 10 == 0 {
                    let ys = self.computePoints()
                    dispatch_async(dispatch_get_main_queue()) {
                        self.updatePoints(ys)
                    }
                }
                ++epoch
            }
        }
    }
    
    /// Returns new y coordinates for each point from the network
    /// This func must be called on self.networkQueue
    func computePoints() -> [CGFloat] {
        return (0..<self.numPoints).map { index -> CGFloat in
            let x = (-500 + (Float(index) * 1000) / Float(self.numPoints)) / 100
            let networkY = try! self.network.update(inputs: [x]).first!
            return CGFloat(networkY * -250) + 125
        }
    }
    
    /// Updates the points on screen with the given y coordinates.
    /// This func must be called on the main queue
    func updatePoints(ys: [CGFloat]) {
        for index in 0..<self.numPoints {
            self.updatePoint(index, y: ys[index])
        }
    }
    
    func pauseTraining() {
{'fraction_non_alphanumeric': 0.10291188466280944, 'fraction_numerical': 0.010433462961206487, 'mean_word_length': 2.327232565478069, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5520907', 'n_tokens_mistral': 3089, 'n_tokens_neox': 2900, 'n_words': 759}