Alloy Analyzer not providing an instance - analyzer

I am trying to make a traffic light model in Alloy. The problem is that I don't really understand it well. I have been reading the traffic light example found with the analyzer, but for some reason it's not giving me any instance. This is the example code.
`module chapter4/lights ----- The model from page 127
abstract sig Color {}
one sig Red, Yellow, Green extends Color {}
sig Light {}
sig LightState {color: Light -> one Color}
sig Junction {lights: set Light}
fun redLights [s: LightState]: set Light { s.color.Red }
fun colorSequence: Color -> Color {
Color <: iden + Red->Green + Green->Yellow + Yellow->Red
}
pred mostlyRed [s: LightState, j: Junction] {
lone j.lights - redLights[s]
}
pred trans [s, s': LightState, j: Junction] {
lone x: j.lights | s.color[x] != s'.color[x]
all x: j.lights |
let step = s.color[x] -> s'.color[x] {
step in colorSequence
step in Red->(Color-Red) => j.lights in redLights[s]
}
}
assert Safe {
all s, s': LightState, j: Junction |
mostlyRed [s, j] and trans [s, s', j] => mostlyRed [s', j]
}
check Safe for 3 but 1 Junction`
If someone can please explain this, I would really appreciate it.

To see an instance, you need to include a run command. The only command you have here is a check command, and if the property checked is true, no counterexample will be found.

Related

Parsing a string to an enum in F#

I am trying to do the following (which doesn't compile):
let Parse<'T> value =
Enum.Parse(typedefof<'T>, value) :?> 'T
In short I would like to pass an enum type, and a string and get back an enum value.
An example usage would be:
type MyEnums =
| Green = 0,
| Blue = 1
and then:
let r = Parse<MyEnums> "Green"
what would be the syntax? I haven't used generics yet in F#, so this is what I came up with from reading the docs.
bonus question would be if there is a way to parse enums in a case insensitive way (besides turning everything to lowercase for example)
This does compile for me (also without true, did you open System?):
let Parse<'T> value =
System.Enum.Parse(typedefof<'T>, value, true) :?> 'T
and works case-insensitive for
type MyEnums =
| Green = 0
| Blue = 1
Parse<MyEnums> "Green" // Green
Parse<MyEnums> "blue" // Blue
I came up with this in a hurry, which I believe has the advantage of not accepting other types than enums. Haven't had time to google for a better way, if there is one. Also, the underlying type must be int, and I haven't had time to see if there's something to be done with that either.
type MyEnum = | A = 1 | B = 2
let parseEnum<'T when 'T : (new : unit -> 'T) and 'T : struct and 'T :> ValueType and 'T : enum<int>> v =
match Enum.TryParse<'T> v with
| true, v -> Some v
| false, _ -> None
let x = parseEnum<MyEnum> "B"
match x with
| Some x -> printfn "%A" x
| None -> printfn "Sorry"
// let z = parseEnum<int> "1" // won't compile

Mata error 3204

I am unsure why I am getting an error.
I think it may stem from a misunderstanding around the structure syntax, but I am not certain if this is the issue (it would be unsurprising if there are multiple issues).
I am emulating code (from William Gould's The Mata Book) in which the input is a scalar, but the input for the program I am writing is a colvector.
The objective of this exercise is to create a square matrix from a column vector (according to some rules) and once created, multiply this square matrix by itself.
The code is the following:
*! spatial_lag version 1.0.0
version 15
set matastrict on
//--------------------------------------------------------------
local SL struct laginfo
local RS real scalar
local RC real colvector
local RM real matrix
//--------------------------------------------------------------
mata
`SL'
{
//-------------------inputs:
`RC' v
//-------------------derived:
`RM' W
`RM' W2
`RS' n
}
void lagset(`RC' v)
{
`SL' scalar r
// Input:
r.v = v
//I set the derived variables to missing:
r.W = .z
r.W2 = .z
r.n = .z // length of vector V
}
`RM' w_mat(`SL' scalar r)
{
if (r.W == .z) {
real scalar row, i
real scalar col, j
r.W = J(r.n,r.n,0)
for (i=1; i<=r.n; i++) {
for (i=1; i<=r.n; i++) {
if (j!=i) {
if (r.v[j]==r.v[i]) {
r.W[i,j] = 1
}
}
}
}
}
return(r.W)
}
`RS' wlength(`SL' scalar r)
{
if (r.n == .z) {
r.n = length(r.v)
}
return(r.n)
}
`RM' w2mat(`SL' scalar r)
{
if (r.W2 == .z) {
r.W2 = r.W * r.W
}
return(r.W2)
}
end
This compiles without a problem, but it give an error when I attempt to use it interactively as follows:
y=(1\1\1\2\2\2)
q = lagset(y)
w_mat(q)
w2mat(q)
The first two lines run fine, but when I run the last two of those lines, I get:
w_mat(): 3204 q[0,0] found where scalar required
<istmt>: - function returned error
What am I misunderstanding?
This particular error is unrelated to structures. Stata simply complains because the lagset() function is void. That is, it does not return anything. Thus, q ends up being empty, which is in turn used as input in the function w_mat() inappropriately - hence the q[0,0] reference.

Applying popbio "projection.matrix" to multiple fertilities and generate list of matrices

I usually find the answers to my questions by looking around here (I'm glad stackovergflow exists!), but I haven't found the answer to this one... I hope you can help me :)
I am using the projection.matrix() function from the "popbio" package to create transition matrices. In the function, you have to specify the "stage" and "fate" (both categorical variables), and the "fertilities" (a numeric column).
Everything works fine, but I would like to apply the function to 1:n fertility columns within the data frame, and get a list of matrices generated from the same categorical variables with the different fertility values.
This is how my data frame looks like (I only include the variables I am using for this question):
stage.fate = data.frame(replicate(2, sample(0:6,40,rep=TRUE)))
stage.fate$X1 = as.factor(stage.fate$X1)
stage.fate$X2 = as.factor(stage.fate$X2)
fertilities = data.frame(replicate(10,rnorm(40, .145, .045)))
df = cbind(stage.fate, fertilities)
colnames(df)[1:2]=c("stage", "fate")
prefix = "control"
suffix = seq(1:10)
fer.names = (paste(prefix ,suffix , sep="."))
colnames(df)[3:12] = c(fer.names)
Using
library(popbio)
projection.matrix(df, fertility=control.1)
returns a single transition matrix with the fertility values incorporated into the matrix.
My problem is that I would like to generate a list of matrices with the different fertility values in one go (in reality the length of my data is >=300, and the fertility columns ~100 for each of four different treatments...).
I will appreciate your help!
-W
PS This is how the function in popbio looks like:
projection.matrix =
function (transitions, stage = NULL, fate = NULL, fertility = NULL,
sort = NULL, add = NULL, TF = FALSE)
{
if (missing(stage)) {
stage <- "stage"
}
if (missing(fate)) {
fate <- "fate"
}
nl <- as.list(1:ncol(transitions))
names(nl) <- names(transitions)
stage <- eval(substitute(stage), nl, parent.frame())
fate <- eval(substitute(fate), nl, parent.frame())
if (is.null(transitions[, stage])) {
stop("No stage column matching ", stage)
}
if (is.null(transitions[, fate])) {
stop("No fate column matching ", fate)
}
if (missing(sort)) {
sort <- levels(transitions[, stage])
}
if (missing(fertility)) {
fertility <- intersect(sort, names(transitions))
}
fertility <- eval(substitute(fertility), nl, parent.frame())
tf <- table(transitions[, fate], transitions[, stage])
T_matrix <- try(prop.table(tf, 2)[sort, sort], silent = TRUE)
if (class(T_matrix) == "try-error") {
warning(paste("Error sorting matrix.\n Make sure that levels in stage and fate columns\n match stages listed in sort option above.\n Printing unsorted matrix instead!\n"),
call. = FALSE)
sort <- TRUE
T_matrix <- prop.table(tf, 2)
}
T_matrix[is.nan(T_matrix)] <- 0
if (length(add) > 0) {
for (i in seq(1, length(add), 3)) {
T_matrix[add[i + 0], add[i + 1]] <- as.numeric(add[i +
2])
}
}
n <- length(fertility)
F_matrix <- T_matrix * 0
if (n == 0) {
warning("Missing a fertility column with individual fertility rates\n",
call. = FALSE)
}
else {
for (i in 1:n) {
fert <- tapply(transitions[, fertility[i]], transitions[,
stage], mean, na.rm = TRUE)[sort]
F_matrix[i, ] <- fert
}
}
F_matrix[is.na(F_matrix)] <- 0
if (TF) {
list(T = T_matrix, F = F_matrix)
}
else {
T_matrix + F_matrix
}
}
<environment: namespace:popbio>
My question was answered via ResearchGate by Caner Aktas
Answer:
fertility.list<-vector("list",length(suffix))
names(fertility.list)<-fer.names
for(i in suffix) fertility.list[[i]]<-projection.matrix(df,fertility=fer.names[i])
fertility.list
Applying popbio “projection.matrix” to multiple fertilities and generate list of matrices?. Available from: https://www.researchgate.net/post/Applying_popbio_projectionmatrix_to_multiple_fertilities_and_generate_list_of_matrices#5578524f60614b1a438b459b [accessed Jun 10, 2015].

constUnsafePointer unresolved identifier in Swift FFT

I have been looking at examples of FFTs in Swift, and they all seem to have ConstUnsafePointer when using vDSP_ctozD as in the example below:
import Foundation
import Accelerate
internal func spectrumForValues(signal: [Double]) -> [Double] {
// Find the largest power of two in our samples
let log2N = vDSP_Length(log2(Double(signal.count)))
let n = 1 << log2N
let fftLength = n / 2
// This is expensive; factor it out if you need to call this function a lot
let fftsetup = vDSP_create_fftsetupD(log2N, FFTRadix(kFFTRadix2))
var fft = [Double](count:Int(n), repeatedValue:0.0)
// Generate a split complex vector from the real data
var realp = [Double](count:Int(fftLength), repeatedValue:0.0)
var imagp = realp
withExtendedLifetimes(realp, imagp) {
var splitComplex = DSPDoubleSplitComplex(realp:&realp, imagp:&imagp)
// Take the fft
vDSP_fft_zripD(fftsetup, &splitComplex, 1, log2N, FFTDirection(kFFTDirection_Forward))
// Normalize
var normFactor = 1.0 / Double(2 * n)
vDSP_vsmulD(splitComplex.realp, 1, &normFactor, splitComplex.realp, 1, fftLength)
vDSP_vsmulD(splitComplex.imagp, 1, &normFactor, splitComplex.imagp, 1, fftLength)
// Zero out Nyquist
splitComplex.imagp[0] = 0.0
// Convert complex FFT to magnitude
vDSP_zvmagsD(&splitComplex, 1, &fft, 1, fftLength)
}
// Cleanup
vDSP_destroy_fftsetupD(fftsetup)
return fft
}
// To get rid of the `() -> () in` casting
func withExtendedLifetime<T>(x: T, f: () -> ()) {
return Swift.withExtendedLifetime(x, f)
}
// In the spirit of withUnsafePointers
func withExtendedLifetimes<A0, A1>(arg0: A0, arg1: A1, f: () -> ()) {
return withExtendedLifetime(arg0) { withExtendedLifetime(arg1, f) }
}
However when I try to use it in my project, this ConstUnsafePointer is seen as an unresolved identifier. Any clue how to fix this? Thanks in advance.
The name ConstUnsafePointer was used in early Swift betas last summer (at that time, UnsafePointer meant mutable). Now, constant pointers are just UnsafePointer and mutable pointers are UnsafeMutablePointer.

Problem with Maze Algorithm

I am having a problem with a algorithm that is designed to solve mazes.
I used an algorithm from here.http://www.cs.bu.edu/teaching/alg/maze/
FIND-PATH(x, y)
if (x,y outside maze) return false
if (x,y is goal) return true
if (x,y not open) return false
mark x,y as part of solution path
if (FIND-PATH(North of x,y) == true) return true
if (FIND-PATH(East of x,y) == true) return true
if (FIND-PATH(South of x,y) == true) return true
if (FIND-PATH(West of x,y) == true) return true
unmark x,y as part of solution path
return false
It is a recursive solution , i modified it such that it will continue even after finding exit so that it can find other solutions as well. It seems to work , just that it seems to find half the total number of solutions that i know are possible.
if (x,y is goal) return true is changed to return false.
Anyone know what might be the problem with such an algorithm resulting in half the number of total possible solutions? I also have a problem into finding the total number of dead end paths, any suggestions on that?
what seems to be missing is the check if X&Y has already been marked as part of the solution, and if so we abort. (this should be somewhere on point 3.5)
If not a maze with a possible loop somewhere would run indefinately and blow up the stack
by the way, from what I read the algorithm is based on a maze with only 1 solution
R
Rather than trying to find one way through the maze, you need to find (and therefore map) multiple ways through the maze.
In order to do this, you need to mark where you've been (on a particular path). If you reach a point you've already been to, you need to flag that route as a dead end.
A recursive function is still the way to go, but make sure that you pass the (placesIhaveBeen) structure through the recursive function.
The recursive loop needs to break when you get to a point where N,S,E,W are all blocked. (You've been there before, you can't go in that direction, it's outside the maze)
The recursive loop also needs to break when you reach your target.
If you get to your target - increase a Global Variable by one.
If you've nowhere to go - increase your dead-ends by one.
I can't write the pcode for this (it'll take too long), but I believe that the secret is in a function that returns true if N, S, E and W are all blocked.
Addition to my initial answer
With regard to why I treat areas I've been to as "blocked", and why I treat them as dead ends....
########
# #
# #### #
####### # # #
# # #
####### # # #
# #### #
# #
########
I would classify the above maze part as a dead end, and I can't see how I can identify it as such without treating places I've been to as blocked areas.
I realise that this would cause the following to also show dead ends, but I can't see a way around it.
#######
# #
# ### #
####### #G# #
# # #
####### # #
# ### #
# #
#######
For the number of dead ends, you need something like that:
3.5 if (North of x,y not open) and (South of x,y not open) and (West of x,y not open) and (East of x,y not open) deadends++
This is a sample maze
####################
#S # # # #
# # ## ## ### ###
# # # # #
## # # # ## #
# ### ##### #
# # # # # ###
# ### ### ## # #####
# # # E#
####################
I tried making a simple-minded implementation of the algorithm in java. My conlusion was that the algorithm you described works, even for finding multiple paths. Or, possibly, you managed to think of a more clever test case than me. (Please post your maze so I can try my algorithm on it)
My implementation of the dead end counter is probably not the most efficient one, but it gets the job done. For each current OPEN node that is visited, it checks the 4 surrounding nodes:
If at least one neighbour is OPEN, current node is not a dead end
If more than one neighbour is VISITED current node is not a dead end
If only one node is VISITED (the one we came from in the previous step) and no other neighbour is OPEN, current node is a dead end
This is the java code I wrote (beware! pretty long). An alternative would be, if you wish, to store the path on a stack, pushing a node each time it is set to VISITED and popping a node each time it is set back to OPEN. Each time the GOAL is reached, the stack holding the current path should be copied and saved.
If the if block marked with a comment as "dead-end-investigation-step" is removed, this implementation is almost exactly equal to the one described in the question.
package test;
import java.util.HashSet;
import java.util.Set;
public class MazeSolver {
final static int OPEN = 0;
final static int WALL = 1;
final static int GOAL = 2;
final static int VISITED = 3;
static int[][] field = { { 0, 0, 0, 0, 0, 1 }, { 1, 0, 1, 1, 0, 1 },
{ 1, 0, 1, 0, 0, 0 }, { 0, 0, 0, 0, 1, 2 }, { 1, 0, 1, 0, 0, 0 } };
// This is what the field looks like:
//
// 0 1 1 0 1
// 0 0 0 0 0
// 0 1 1 0 1
// 0 1 0 0 0
// 0 0 0 1 0
// 1 1 0 2 0
static int width = field.length;
static int height = field[0].length;
static int xStart = 0;
static int yStart = 0; // Initiated to start position: (x = 0, y = 0)
static int nrSolutions = 0; // Records number of solutions
// Used for storing id:s of dead end nodes.
// The integer id is (x + y * width)
static Set<Integer> deadEnds = new HashSet<Integer>();
public static void main(String[] arg) {
System.out.println("Initial maze:");
printField();
findPath(xStart, yStart);
System.out.println("Number of solutions: " + nrSolutions);
System.out.println("Number of dead ends: " + deadEnds.size());
}
private static void findPath(int x, int y) {
if (x < 0 || y < 0 || x >= width || y >= height) { // Step 1
return;
} else if (field[x][y] == GOAL) { // Step 2
nrSolutions++;
System.out.println("Solution nr " + nrSolutions + ":");
printField();
return;
} else if (field[x][y] != OPEN) { // Step 3
return;
} else if (isDeadEnd(x, y)) { // Extra dead-end-investigation-step
int uniqueNodeId = x + y * width;
deadEnds.add(uniqueNodeId); // Report as dead end
return;
}
field[x][y] = VISITED; // Step 4
findPath(x, y - 1); // Step 5, go north
findPath(x + 1, y); // Step 6, go east
findPath(x, y + 1); // Step 7, go south
findPath(x - 1, y); // Step 8, go west
field[x][y] = OPEN; // Step 9
// Step 10 is not really needed, since the boolean is intended to
// display only whether or not a solution was found. This implementation
// uses an int to record the number of solutions instead.
// The boolean return value would be (nrSolutions != 0)
}
private static boolean isDeadEnd(int x, int y) {
int nrVisitedNeighbours = 0;
if (y > 0) { // If northern neighbour exists
if (field[x][y - 1] == VISITED) {
nrVisitedNeighbours++;
} else if (field[x][y - 1] != WALL) {
return false;
}
}
if (x < width - 1) { // If eastern neighbour exists
if (field[x + 1][y] == VISITED) {
nrVisitedNeighbours++;
} else if (field[x + 1][y] != WALL) {
return false;
}
}
if (y < height - 1) { // If southern neighbour exists
if (field[x][y + 1] == VISITED) {
nrVisitedNeighbours++;
} else if (field[x][y + 1] != WALL) {
return false;
}
}
if (x > 0) { // If western neighbour exists
if (field[x - 1][y] == VISITED) {
nrVisitedNeighbours++;
} else if (field[x - 1][y] != WALL) {
return false;
}
}
if (nrVisitedNeighbours > 1) { // Circular path scenario
return false;
}
return true; // The exhaustive result of this check: this is a dead
// end
}
private static void printField() {
for (int yy = 0; yy < field[0].length; yy++) {
for (int xx = 0; xx < field.length; xx++) {
System.out.print(field[xx][yy] + " ");
}
System.out.println();
}
System.out.println();
}
}
The algorithm above reports four different solution paths and two dead ends to the example maze which is hardcoded into the code.
<EDIT>
Might the reason for why you get too few solution paths be a misinterpretation of what is a solution path? For example, consider this maze:
######
## #
## # #
#S #
##E###
######
This maze has only one valid solution path. This is because you are only allowed to visit each node once, so going around the circular path is not a valid solution path since that would visit the node east of S and north of E twice. This definition of a solution path is implied by the algorithm that you use.
If one were to allow visiting the same node multiple times, there would be infinitely many solutions, as you could go around the circle 1, 2, 3 ... to infinitely many times.
</EDIT>
<EDIT2>
Exactly as you say, I increase the pathLength each time I set a node to VISITED, and decrease the path length each time I set a VISITED node back to OPEN.
To record the shortest path length I also have a shortestPath int value which I initiate to Integer.MAX_VALUE. Then, each time I have reached the goal, I do this:
if(pathLength < shortestPath){
shortestPath = pathLength;
}
As for the dead ends... I tried counting them by hand and I thought 9 seemed right. Here is the maze posted by Sareen, but with the dead ends marked (by hand) with a D:
####################
#S # D# D#D D#
# # ## ## ### ###
# # # # #
## # # # ## #
# ### ##### #
# # #D #D # ###
# ### ### ## # #####
# D#D #D E#
####################
Can you find any more?
Or did I misinterpret what you meant by dead end?
I thought dead end means: A node to which you can only come from one direction.
Example 1:
######
## ###
## ###
## ###
#S E#
######
The maze above has one dead end.
Example 2:
######
## ##
## ##
## ##
#S E#
######
The above maze has no dead ends. Even if you are at one of the accessible nodes furthest to the north, there are still two adjacent non-WALL squares.
Do you have another definition of dead end?
</EDIT2>

Resources