I'm trying to implement the answer to this question: https://stackoverflow.com/questions/3704647/can-you-recommend-a-charting-library-for-scala/3704974#3704974
I've downloaded and compiled Scalala from the git hub and placed the scalala_2.8.1-1.0.0.RC2-SNAPSHOT.jar in my lib folder (I'm using SBT to do my build). Here's the code:
import scalala.library.Plotting
object ScalalaTest extends Application
{
val x = Plotting.linspace(0,1);
}
I'm getting the following error:
[error] /src/main/scala/ScalalaTest.scala:6: value linspace is not a member of object scalala.library.Plotting
[error] val x = Plotting.linspace(0,1);
[error] ^
[error] one error found
It looks like my scala compiler recognizes the scalala package but doesn't recognize members of Plotting (I've tried others besides linspace). This is strange because according to the Scalala API, linspace is a member of Plotting.
That used to work and was nice and elegant - it seems the current way is:
val x = DenseVector.range(0,100) / 100.0;
plot.hold = true
plot(x, x :^ 2)
plot(x, x :^ 3, '.')
xlabel("x axis")
ylabel("y axis")
saveas("lines.png")
This needs includes:
import scalala.tensor.dense.DenseVector
import scalala.library.Plotting._
The SBT dependencies are:
val scalaToolsSnapshots = "Scala Tools Snapshots" at "http://scala-tools.org/repo-snapshots/"
val ScalaNLPMaven2 = "ScalaNLP Maven2" at "http://repo.scalanlp.org/repo/"
val ondex = "ondex" at "http://ondex.rothamsted.bbsrc.ac.uk/nexus/content/groups/public/"
val scalala = "org.scalala" %% "scalala" % "1.0.0.RC2-SNAPSHOT"
linspace seems to be a member of the trait Plotting, not of the companion object. So you'll have to create an instance of Plotting (or anything with Plotting) in order to access that method.
Related
I am new with Numba. I am trying to accelerate a pretty complicated solver. However, I keep getting an error such as
numba.core.errors.TypingError: Failed in nopython mode pipeline (step: nopython frontend) Untyped global name 'isinstance': Cannot determine Numba type of <class 'builtin_function_or_method'>
I wrote a small example to reproduce the same error:
import numba
import numpy as np
from numba import types
from numpy import zeros_like, isfinite
from numpy.linalg import solve
from numpy.random import uniform
#numba.njit(parallel=True)
def foo(A_, b_, M1=None, M2=None):
x_ = zeros_like(b_)
r = b_ - A_.dot(x_)
flag = 1
if isinstance(M1, types.NoneType): # Error here
y = r
else:
y = solve(M1, r)
if not isfinite(y).any():
flag = 2
if isinstance(M2, types.NoneType):
z = y
else:
z = solve(M2, y)
if not isfinite(z).any():
flag = 2
return z, flag
N = 10
tmp = np.random.rand(N, N)
A = np.dot(tmp, tmp.T)
x = np.zeros((N, 1), dtype=np.float64)
b = np.vstack([uniform(0.0, 1.0) for i in range(N)])
X_1, info = foo(A, b)
Also if I change the decorator to generated_jit() I get the following error:
r = b_ - A_.dot(x_)
AttributeError: 'Array' object has no attribute 'dot'
Numba compiles the function and requires every variables to be statically typed. This means that each variable has only one unique type: one variable cannot be of both the type NoneType and something else as opposed to with CPython based on dynamic typing. Dynamic typing is also a major source of the slowdown of CPython. Thus, using isinstance in nopython JITed Numba functions does not make much sense. In fact, this built-in function is not supported.
That being said, Numba supports optional arguments by specifying optional(ArgumentType) in the signature (note that the resulting type of the variable is optional(ArgumentType) and not ArgumentType nor NoneType. You can then test if the argument is set using if yourArgument is None:. I do not know what is the type of M1 and M2 in your code but they need to be explicitly defined in the signature with optional argument.
I have a code which gets the colormap of an image(*.tif).
val geotiff = SinglebandGeoTiff(abcd.tif)
val colorMap1 = geotiff.options.colorMap
Now colorMap1 is of type IndexedColorMap.
Is there a way to convert or typecast colormap1 to ColorMap(geotrellis.raster.render.ColorMap) , because my whole code is based on ColorMap and not on IndexedColorMap
IndexedColorMap extends IntColorMap which extends ColorMap so they are compatible. But it looks like geotiff.options.colorMap is returning Option[IndexedColourMap] not IndexedColorMap. So you can do this:
val defaultColorMap: ColorMap = ???
val colorMap1: ColorMap = geotiff.options.colorMap.getOrElse(defaultColorMap)
See online for other ways to process Option values in Scala in a clean, functional way.
I'm trying to cram brush up on Scala for a job I got, and I'm looking into implicit classes. So far they seem quite handy in making code more readable, but I've run into a problem that I can't figure out.
In this code, I'm implementing some common vector operations, and for the most part they seem to be running just fine. However, when I added the norm method, the magn method started throwing errors. My operating script is thus:
import scala.language.postfixOps
import scala.math.sqrt
case class Vector(x: Double, y: Double)
object VMath {
implicit class VectorMath(v1: Vector) {
def dot(v2: Vector): Double = v1.x * v2.x + v1.y * v2.y
def cross(v2: Vector): Double = v1.x * v2.y - v1.y * v2.x
def magn(): Double = sqrt(v1.x * v1.x + v1.y * v1.y)
def norm(): Vector = Vector(v1.x / magn, v1.y / magn)
}
}
import VMath._
val a = Vector(1.0, 2.0)
val b = Vector(3.0, 4.0)
a dot b
a cross b
a magn
a norm
Whenever I run this code, the line a magn throws an error that reads
no arguments allowed for nullary method magn: ()Double
It had no problem running before I implemented the norm method, and it has no problems within the norm method. I'm not sure if this is due to my misunderstanding of how Scala itself works, how postfixObs works, how implicit classes work, how single line methods work, or if it's just some stupid typo that I'm missing, but this has got me tearing my hair out. (And I happen to like my hair, so...)
My code can be tested and the problem recreated on Scastie: https://scastie.scala-lang.org/0jvrx4lYQwauBpN6IZtSPA
Postfix notation (dot-less) can be used when the method takes no argument, but you have to help the compiler figure it out.
a magn
a norm;
A blank line, or a semicolon, tells the compiler to stop looking for the argument to pass to the method. It's not coming.
It's usually better to reserve dot-less notation for only the simplest, most obvious, declarations (with all 3 pieces).
Seems like compiler got confused and treated a in the last line as argument to magn method. There is nothing wrong with your implementation of norm method.
Possible fixes
add dots -> a.magn
terminate line with semicolon a magn;
introduce empty paranthesis a magn()
I am writing a code to perform kernel K-Means (aka https://en.wikipedia.org/wiki/K-means_clustering, but with a trick). I need to generate data, and as a first simple generator I tried to implement a Gaussian Mixture Model. Here are my code:
package p02kmeans
import breeze.linalg._
import breeze.stats.distributions._
/**
* First data generation is simple, gaussian mixture model.
*/
object Data {
class GaussianClassParam (
val mean: Double,
val sd: Double)
/**
* #param proportion marginal probability for each label
* #param param param[j][k] returns the GaussianClassParam for the k class of the j variable
* #param nObs number of observations to be generated
* #result DenseMatrix_ij where i is the observation index and j is the variable number
*/
def gaussianMixture(
proportion: DenseVector[Double],
param: Vector[Vector[GaussianClassParam]],
nObs: Int)
: DenseMatrix[Double] = {
val nVar = param.size
val multiSampler = Multinomial(proportion) // sampler for the latent class
val varSamplerVec = param.map(v => v.map(c => Gaussian(c.mean, c.sd)))
val zi = DenseVector.fill[Int](nObs)(multiSampler.sample)
val data = DenseMatrix.tabulate[Double](nObs, nVar)((i, j) => varSamplerVec(j)(zi(i)).sample)
return data
}
}
When I try to compile my code (I use Scala-Ide and sbt eclipse on Windows 10) I get 2 errors:
Error in Scala compiler: assertion failed: List(method apply$mcI$sp, method apply$mcI$sp)
SBT builder crashed while compiling. The error message is 'assertion failed: List(method apply$mcI$sp, method apply$mcI$sp)'. Check Error Log for details.
The error is triggered by the line:
val data = DenseMatrix.tabulate[Double](nObs, nVar)((i, j) => varSamplerVec(j)(zi(i)).sample)
And disappear with:
val data = DenseMatrix.tabulate[Double](nObs, nVar)((i, j) => 12.0)
Could you help me debug this ?
My sbt configuration:
name := "Sernel"
version := "1.0"
scalaVersion := "2.11.8"
libraryDependencies ++= Seq(
"org.scalanlp" %% "breeze" % "0.13.1",
"org.scalanlp" %% "breeze-natives" % "0.13.1",
"org.scalanlp" %% "breeze-viz" % "0.13.1"
)
I have the same errors on my OSX setup.
If you want to test the whole package (as, if you want to reproduce the error), the code is available on Github: https://github.com/vkubicki/sernel, and I am available to provide directions :).
It seems like it's a compiler bug (I suppose in scala macroses as Breeze is using those). You could try to perform total clean in the project (maybe even including .ivy2 folder - this could be a difference between your MacOS and Windows setup) and also update your scala to 2.11.11 (or maybe even 2.12.x)
However, similar issue with Scala 2.11.6 (and something tells me it's inherited in subsequent versions of Scala) wasn't fixed: https://issues.scala-lang.org/browse/SI-9284
So probably, you'll have to repeatedly perform cleaning sometimes or maybe try some other NumPy analogs like: scalala, Nd4j/Ndjs.
It could also help to try another IDE (IDEA/Atom) or try to use "bare" SBT as Eclipse is probably interfering by calling Scala's compiler front-end.
I have not enough reputation to create tag "ScalaLab" :(
I'm studying ScalaLabAllDraftUserGuideJune142013.pdf
When I enter first example:
var a = ones0(20, 30) // creates a zero-indexed 20X30 matrix filled with ones
var b = ones0(30, 50)
var c = a * b
console displays:
<console>:7: error: not found: value ones0
var a = ones0(20, 30) // creates a zero-indexed 20X30 matrix filled with ones
^
<console>:8: error: not found: value ones0
var b = ones0(30, 50)
^
Error
Imports do not help.
Could anyone help?
Thank you! I solved this at
https://code.google.com/p/scalalab/issues/detail?id=15
From the "Scala Interpreter" menu,
you can choose the preferred library (EJML works faster),
and then all the ScalaLab imported routines (as e.g. ones0)
will work well.
... it's better to avoid JEIGEN library, because the native routines,
currently do not work on Windows, but they work on Linux