scala.util.DynamicVariable Scala Examples

The following examples show how to use scala.util.DynamicVariable. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: Signal.scala    From LearningScala   with Apache License 2.0 5 votes vote down vote up
package _070_timely_effects._02_functional_reactive_programming

import scala.util.DynamicVariable

class Signal[T](expr: => T) {

  import Signal._

  private var myExpr: () => T = _
  private var myValue: T = _
  private var observers: Set[Signal[_]] = Set()
  update(expr)

  protected def update(expr: => T): Unit = {
    myExpr = () => expr
    computeValue()
  }

  def computeValue(): Unit = {
    val newValue = caller.withValue(this)(myExpr())
    if (myValue != newValue) {
      myValue = newValue
      val obs = observers
      observers = Set()
      obs.foreach(_.computeValue())
    }
  }

  def apply(): T = {
    observers += caller.value
    assert(!caller.value.observers.contains(this), "Cyclic signal definition")
    myValue
  }
}

object NoSignal extends Signal[Nothing](???){
  override def computeValue(): Unit = ()
}

object Signal {
//  val caller = new StackableVariable[Signal[_]](NoSignal)
  val caller = new DynamicVariable[Signal[_]](NoSignal)

  def apply[T](expr: => T) = new Signal(expr)
} 
Example 2
Source File: Signal.scala    From Principles-of-Reactive-Programming   with GNU General Public License v3.0 5 votes vote down vote up
package calculator

import scala.util.DynamicVariable

class Signal[T](expr: => T) {
  import Signal._
  private var myExpr: () => T = _
  private var myValue: T = _
  private var observers: Set[Signal[_]] = Set()
  private var observed: List[Signal[_]] = Nil
  update(expr)

  protected def computeValue(): Unit = {
    for (sig <- observed)
      sig.observers -= this
    observed = Nil
    val newValue = caller.withValue(this)(myExpr())
    
    //if (myValue != newValue) {
      myValue = newValue
      val obs = observers
      observers = Set()
      obs.foreach(_.computeValue())
    //}
  }

  protected def update(expr: => T): Unit = {
    myExpr = () => expr
    computeValue()
  }

  def apply() = {
    observers += caller.value
    assert(!caller.value.observers.contains(this), "cyclic signal definition")
    caller.value.observed ::= this
    myValue
  }
}

class Var[T](expr: => T) extends Signal[T](expr) {
  override def update(expr: => T): Unit = super.update(expr)
}

object Var {
  def apply[T](expr: => T) = new Var(expr)
}

object NoSignal extends Signal[Nothing](???) {
  override def computeValue() = ()
}

object Signal {
  val caller = new DynamicVariable[Signal[_]](NoSignal)
  def apply[T](expr: => T) = new Signal(expr)
} 
Example 3
Source File: Driver.scala    From dsptools   with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
// See LICENSE for license details.

package dsptools

import chisel3._
import chisel3.iotesters._
import firrtl.HasFirrtlOptions
import numbers.{DspRealFactory, TreadleDspRealFactory}
import firrtl_interpreter._
import treadle.HasTreadleOptions

import scala.util.DynamicVariable

object Driver {

  private val optionsManagerVar = new DynamicVariable[Option[DspTesterOptionsManager]](None)
  def optionsManager = optionsManagerVar.value.getOrElse(new DspTesterOptionsManager)

  def execute[T <: MultiIOModule](dutGenerator: () => T,
      optionsManager: TesterOptionsManager)(testerGen: T => PeekPokeTester[T]): Boolean = {

    val om = optionsManager match {
      case d: DspTesterOptionsManager => Some(d)
      case _ => None
    }

    optionsManagerVar.withValue(om) {
      optionsManager.interpreterOptions = optionsManager.interpreterOptions.copy(
          blackBoxFactories = optionsManager.interpreterOptions.blackBoxFactories :+ new DspRealFactory
      )
      optionsManager.treadleOptions = optionsManager.treadleOptions.copy(
        blackBoxFactories = optionsManager.treadleOptions.blackBoxFactories :+ new TreadleDspRealFactory
      )
      iotesters.Driver.execute(dutGenerator, optionsManager)(testerGen)
    }

  }

  def execute[T <: MultiIOModule](dutGenerator: () => T,
      args: Array[String] = Array.empty)(testerGen: T => PeekPokeTester[T]): Boolean = {

    val optionsManager = new DspTesterOptionsManager {
      interpreterOptions = interpreterOptions.copy(
          blackBoxFactories = interpreterOptions.blackBoxFactories :+ new DspRealFactory
      )
      treadleOptions = treadleOptions.copy(
        blackBoxFactories = treadleOptions.blackBoxFactories :+ new TreadleDspRealFactory
      )
    }

    if (optionsManager.parse(args)) execute(dutGenerator, optionsManager)(testerGen)
    else {
      optionsManager.parser.showUsageAsError()
      false
    }
  }

  def executeFirrtlRepl[T <: MultiIOModule](dutGenerator: () => T,
      optionsManager: ReplOptionsManager = new ReplOptionsManager): Boolean = {

    optionsManager.chiselOptions = optionsManager.chiselOptions.copy(runFirrtlCompiler = false)
    optionsManager.firrtlOptions = optionsManager.firrtlOptions.copy(compilerName = "low")
    optionsManager.interpreterOptions = optionsManager.interpreterOptions.copy(
        blackBoxFactories = optionsManager.interpreterOptions.blackBoxFactories :+ new DspRealFactory
    )
    optionsManager.treadleOptions = optionsManager.treadleOptions.copy(
      blackBoxFactories = optionsManager.treadleOptions.blackBoxFactories :+ new TreadleDspRealFactory
    )

    logger.Logger.makeScope(optionsManager) {
      val chiselResult: ChiselExecutionResult = chisel3.Driver.execute(optionsManager, dutGenerator)
      chiselResult match {
        case ChiselExecutionSuccess(_, emitted, _) =>
          optionsManager.replConfig = ReplConfig(firrtlSource = emitted)
          FirrtlRepl.execute(optionsManager)
          true
        case ChiselExecutionFailure(message) =>
          println("Failed to compile circuit")
          false
      }
    }
  }

}

class ReplOptionsManager
  extends InterpreterOptionsManager
    with HasInterpreterOptions
    with HasChiselExecutionOptions
    with HasFirrtlOptions
    with HasReplConfig
    with HasTreadleOptions 
Example 4
Source File: ThreadUtils.scala    From boson   with Apache License 2.0 5 votes vote down vote up
package io.zink.utils

import java.util.concurrent._
import scala.util.DynamicVariable

object ThreadUtils {

  val forkJoinPool = new ForkJoinPool

  
  def parallel[A, B, C, D](taskA: => A, taskB: => B, taskC: => C, taskD: => D): (A, B, C, D) = {
    val ta = task {
      taskA
    }
    val tb = task {
      taskB
    }
    val tc = task {
      taskC
    }
    val td = taskD
    (ta.join(), tb.join(), tc.join(), td)
  }
} 
Example 5
Source File: package.scala    From tensorflow_scala   with Apache License 2.0 5 votes vote down vote up
package org.platanios.tensorflow.api.learn

import org.platanios.tensorflow.api.core.types.TF
import org.platanios.tensorflow.api.core.{Graph, Shape}
import org.platanios.tensorflow.api.ops.{OpSpecification, Output}
import org.platanios.tensorflow.api.ops.variables._

import scala.util.DynamicVariable


package object layers {
  trait ParameterGetter {
    def get[T: TF](
        name: String,
        shape: Shape,
        initializer: Initializer = null,
        regularizer: Regularizer = null,
        trainable: Boolean = true,
        reuse: Reuse = ReuseOrCreateNew,
        collections: Set[Graph.Key[Variable[Any]]] = Set.empty,
        cachingDevice: OpSpecification => String = null
    ): Output[T]

    def apply[T: TF](
        name: String,
        shape: Shape,
        initializer: Initializer = null,
        regularizer: Regularizer = null,
        trainable: Boolean = true,
        reuse: Reuse = ReuseOrCreateNew,
        collections: Set[Graph.Key[Variable[Any]]] = Set.empty,
        cachingDevice: OpSpecification => String = null
    ): Output[T] = {
      get(name, shape, initializer, regularizer, trainable, reuse, collections, cachingDevice)
    }
  }

  private[layers] val parameterGetter: DynamicVariable[ParameterGetter] = {
    new DynamicVariable[ParameterGetter](DefaultParameterGetter)
  }

  private object DefaultParameterGetter extends ParameterGetter {
    override def get[T: TF](
        name: String,
        shape: Shape,
        initializer: Initializer = null,
        regularizer: Regularizer = null,
        trainable: Boolean = true,
        reuse: Reuse = ReuseOrCreateNew,
        collections: Set[Graph.Key[Variable[Any]]] = Set.empty,
        cachingDevice: OpSpecification => String = null
    ): Output[T] = {
      Variable.getVariable[T](
        name, shape, initializer, regularizer, trainable, reuse, collections, cachingDevice
      ).value
    }
  }

  private[api] trait API
      extends Activation.API
          with Basic.API
          with Embedding.API
          with Input.API
          with Layer.API
          with Loss.API
          with Math.API
          with NN.API
          with Summary.API
          with core.API
          with rnn.API {
    type ParameterGetter = layers.ParameterGetter

    def withParameterGetter[R](parameterGetter: ParameterGetter)(block: => R): R = {
      layers.parameterGetter.withValue(parameterGetter)(block)
    }
  }

  private[api] object API extends API
} 
Example 6
Source File: package.scala    From tensorflow_scala   with Apache License 2.0 5 votes vote down vote up
package org.platanios.tensorflow.api

import org.platanios.tensorflow.api.core.client.SessionConfig

import scala.collection.compat.immutable.ArraySeq
import scala.util.DynamicVariable


package object tensors {
  private[api] val executionContext: DynamicVariable[Context] = {
    val sessionConfig = sys.env.get("TF_CUDA_VISIBLE_DEVICES")
        .map(devices => SessionConfig(
          gpuVisibleDevices = Some(ArraySeq.unsafeWrapArray(devices.split(',').map(_.toInt)))))
    new DynamicVariable[Context](Context(sessionConfig))
  }

  private[api] trait API
      extends tensors.ops.API
}