Using FRP to model road network with jams - haskell

I am currently trying to understand arrows and FRP, and I came upon a question, which I cannot seem to map to FRP, namely how to model a road network.
I thought I could model a road network as Arrows, where each Arrow represents a road segment. It accepts streams of cars at locations and times and produces the same type, albeit with different locations and times.
So far so good. But this model does not take into account, that segments may get jammed. While each segment could well respond to heavy traffic and delay cars more and more, the more congested it gets, there would be no backwater effect, i.e. the jam would not propagate backwards to other road segments.
I suspect I am applying too much OO thinking here, instead of focusing on what needs to be computed, but I cannot get it right in my head.
How can I model a road network with Arrows such that backwater effects are taken into account?

The problem is that in arrows and in FRP the flow of information is in general unidirectional. Think of a FRP arrow like a piece of digital circuit. The output of a circuit element doesn't depend on what's connected to it - it just "offers" the output to whoever is interested. This is also described visually in Primitive signal functions in the Yampa overview:
Your situation is different. The state of a segment of a road depends on both the next and previous segments - cars are comming from the previous one, but if cars can't leave to the next one, they have to stay. It's just like a pipe with running water. If you close the pipe at its end, water stops, and the information about that propagates backwards through the pipe at the speed of sound in water.
So each road segment will need to have 2 inputs: One saying let's say how many cars can the following segment accept, and how many cars are coming from the previous segment (which should always be less or equal to the number of cars the segment can accept at the moment). This means that the FRP signal flow will be actually circular. For this you'll need loops, shown in the last image in the above diagram, which are captured by ArrowLoop type-class. Most likely you'll have a custom binding function for road segments that'll be internally creating the required loops. Note that there must be a time delay in a loop, to prevent it from diverging, which makes sense as it takes some time for cars to go from one segment to another.
(I'll perhaps expand the answer with an example, if I'll have more time.)

Related

Detecting damaged car parts

I am trying to build a system that on providing an image of a car can assess the damage percentage of it and also find out which parts are damaged in the car.
Is there any possible way to do this using Python and open-cv or tensorflow ?
The GitHub repositories I found that were relevant to my work are these
https://github.com/VakhoQ/damage-car-detector/tree/master/DamageCarDetector
https://github.com/neokt/car-damage-detective
But what they provide is a qualitative output( like they say the car damage is high or low), I wanted to print out a quantitative output( percentage of damage ) along with the individual part names which are damaged
Is this possible ?
If so please help me out.
Thank you.
To extend the good answers given by #yves-daoust: It is not a trivial task and you should not try to do it at once with one single approach.
You should question yourself how a human with a comparable task, i.e. say an expert who reviews these cars after a leasing contract, proceeds with this. Then you have to formulate requirements and also restrictions for your system.
For instance, an expert first checks for any visual occurences and rates these, then they may check technical issues which may well be hidden from optical sensors (i.e. if the car is drivable, driving a round and estimate if the engine is running smoothly, the steering geometry is aligned (i.e. if the car manages to stay in line), if there are any minor vibrations which should not be there and so on) and they may also apply force (trying to manually shake the wheels to check if the bearings are ok).
If you define your measurement system as restricted to just a normal camera sensor, you are somewhat limited within to what extend your system is able to deliver.
If you just want to spot cosmetic damages, i.e. classification of scratches in paint and rims, I'd say a state of the art machine vision application should be able to help you to some extent:
First you'd need to detect the scratches. Bear in mind that visibility of scratches, especially in the field with changing conditions (sunlight) may be a very hard to impossible task for a cheap sensor. I.e. to cope with reflections a system might need to make use of polarizing filters, special effect paints may interfere with your optical system in a way you are not able to spot anything.
Secondly, after you detect the position and dimension of these scratches in the camera coordinates, you need to transform them into real world coordinates for getting to know the real dimensions of these scratches. It would also be of great use to know the exact location of the scratch on the car (which would require a digital twin of the car - which is not to be trivially done anymore).
After determining the extent of the scratch and its position on the car, you need to apply a cost model. Because some car parts are easily fixable, say a scratch in the bumper, just respray the bumper, but scratch in the C-Pillar easily is a repaint for the whole back quarter if it should not be noticeable anymore.
Same goes with bigger scratches / cracks: The optical detection model needs to be able to distinguish between scratches and cracks (which is very hard to do, just by looking at it) and then the cost model can infer the cost i.e. if a bumper needs just respray or needs complete replacement (because it is cracked and not just scratched). This cost model may seem to be easy but bear in mind this needs to be adopted to every car you "scan". Because one cheap damage for the one car body might be a very hard to fix damage for a different car body. I'd say this might even be harder than to spot the inital scratches because you'd need to obtain the construction plans/repair part lists (the repair handbooks / repair part lists are mostly accessible if you are a registered mechanic but they might cost licensing fees) of any vehicle you want to quote.
You see, this is a very complex problem which is composed of multiple hard sub-problems. The easiest or probably the best way to do this would be to do a bottom up approach, i.e. starting with a simple "scratch detector" which just spots scratches in paint. Then go from there and you easily see what is possible and what is not

Washing machine petri net

It is my first time doing a Petri net, and I want to model a washing machine. I have started and it looks like this so far:
Do you have any corrections or help? I obviously know its not correct, but I am a beginner and not aware of the mistakes you guys might see. Thanks in advance.
First comments on your net's way of working:
there is no arrow back to the off state. So once you switch on your washing machine, won't you never be able to switch it off again ?
drain and dry both conduct back to idle. But when idle has a token, it will either go to delicate or to T1. The conditions ("program" chosen by the operator) don't vanish, so they would be triggered again and again.
Considering the last point, I'd suggest to have a different idle for the end of the program to avoid this cycling. If you have to pass several times through the same state but take different actions depending on the progress, you have to work with more tokens.
Some remarks about the net's form:
you don't need to put the 1 on every arc. You could make this more readable by Leaving the 1 out and indicating a number on an arc, only when more than one tokens would be needed.
usually, the transitions are not aligned with the arcs (although nothing forbids is) but rather perpendicular to the flow (here, horizontal)
In principle, "places" (nodes) represent states or resources, and "transitions" (rectangles) represent an event that changes the state (or an action that consumes resources). Your naming convention should better reflect this
Apparently you're missing some condition to stop the process. Now once you start your washing will continue in an endless loop.
I think it would be nice to leave the transition graphics unshaded or unfilled if it is not enabled. Personally I fill it green if it is enabled.
If you want someone to check if you modeled a logic properly in your Petri Net then it would be nice if you include a description of your system logic in prose.

C++/OpenGL chess game program design advice

I'm making a chess game, rendered with OpenGL.
I'm not looking for somebody to tell me all of the answers, I would like to figure the code out on my own, but pointing me to the right concepts is what I really need. At this point, I'm not sure where to start. Here is what I've figured out:
An enumeration, TurnState, with the following values:
playerOneTurn
playerTwoTurn
Stopped
An enumeration, GameState, with the following values:
playerOneCheck
playerTwoCheck
playerOnecCheckMate
PlayerTwoCheckMate
InitializingGame
Tie
NormalPlay
An abstract class, Player, and a subclass, Computer.
A class, ChessGame, with the following fields:
Player p1, p2
TurnState turnState
GameState gameState
A class, Move, with the following fields:
*Piece
Location origin
Location destination
A class, Location, with the following fields:
row
col
*ChessBoard
A class, ChessBoard, with one method, isValid, which takes a Move and checks if the move is valid or not.
An abstract class, ChessPieces, with the following methods:
GetValue() // returns an int value of the piece (for scoring)
GetPosition() // returns the current position of a piece
getIsSelected() // returns a boolean, true if selected, false if unselected
move() // moves the piece in a way dependent upon what piece
And the following subclasses:
Pawn
Rook
Queen
King
Knight
As to the AI part of the chess game:
To get a chess AI, or any sort of turn based game AI, you will need to calculate the "value" of the game in a given turn (that's important) (i.e. you assign each piece a value and sum the values for player1 and player2 and then you do score = player1score - player2score, so negative values will benefit player 2 and positive ones, player 1, that's just a basic example and not a very efficient one, but it's the most basic way to explain what the "value" of the game would be).
After you can calculate that you need to be able to calculate every possible move of a player given a certain configuration of the board.
With that you will be able to build a decision tree in which you will have as the root node the current state of the game. The next "level" of the tree will represent every possible state you can get to from the current state (and so forth). It's important to notice that if you consider player1 possible moves in on level of the tree you will consider player two possible moves in the next.
Next thing to do would be:
suppose player1 is gonna make a move, he will look into in the tree until depth 5 (for a chess game you'll never look in the whole tree). So he will choose a move that will be optimized for him, that would mean: at each level he'll consider HIS best move or player2's best move (so he will work on the worst case scenario), so he'll move the the highest valued node in the next level of the tree.
To calculate a value of a node you do the following:
NOTE: considering root node is of depth 0, every odd depth node need to be maxValue for player1 and every even depth node minValue for player2.
You'll expand the tree to the max depth you define, for the node in the maxDepth you'll just calculate the value of the board (which I mentioned in the beginning of my answer), for upper nodes you'll do:
even node's value : minValue between all child nodes
odd node's value : maxValue between all child nodes
So basically you'll do the regression to find the value of a node based on the value of deeper nodes.
Well, that's the basic idea, from it you can research some other stuff, if you want you can PM me, I've done some work on this kind of search, and I just described the most basic idea here, for an efficient code you'll need lots of optimization techniques.
Hope it helped a little
First of all: Separate the two: AI and GUI/OpenGL. In chess it is normal to have the GUI and the AI (the "Engine" in computer chess lingo) in two different processes that's communicating with a predefined protocol. The two most popular protocols for this are UCI and WinBoard.
For the chess engine part, you basically need three thing:
A board/position representation
A leaf node evaluation function
A search algorithm
I suggest you read:
Chess Programming WIKI
TalkChess forum for computer chess
Study a open source computer chess engine, like Stockfish, Crafty or Fruit.
This may not be directly answering your question (actually what is your question?), but you mentioned you wanted pointers to the right concepts.
oysteijo is right, one of the concepts that is very important is separating parts of a program from each other.
For something like chess there exist many efficient and elegant representations of the state of a chess game. I would say that the MVC (model, view, controller) design pattern works quite well for a chess game.
Hopefully this will make some sense, if not I suggest you read up on MVC some more.
Your model is going to primarily involve the datastructure which stores the representation of state of the game, this is the chessboard. A piece can only be on one of 64 spots, and there are limitations on the types of pieces and how many there are and what each of them do. The model will be responsible for dealing with this stuff. It would also make sense to give the model the logic for determining the legality of any given move (i.e. the properties of the game which don't necessarily involve the state of any given instance of a game).
The view is where all of your presentation related code goes. All that OpenGL is going in here, as would a "debug" routine which might (for instance) print an ASCII representation of the chessboard to the console.
The controller might have some functions which interface with the user to process input. The controller is the part of code which manipulates the model ("move E5 to D3": a function in your controller might call model.moveKnight('D3')) and the view ("draw the board in glorious 3D": the controller might do something like calling openGLView.draw(model))
One of the primary goals that MVC helps achieve is the independence of parts of code that perform different tasks. If some change in your AI causes problems with a rendering algorithm, it is a frustrating and difficult position to be in. An experienced programmer would go to some great lengths to ensure that this couldn't happen.
You might be wondering at this point where your AI code fits into the picture. Well, it's really up to you. Use your best judgement. It could be a part of the controller. Personally I'd have it be a whole nother controller (chessAIController) which implements the AI algorithms, but it is just as easy to have all of it contained within the main controller.
The point is, it doesn't really matter how you actually organize the code so long as it is done in some kind of logical way. The reason that MVC is so widespread is that those 3 components are usually present in most software and it usually makes sense to separate them. Note they're not actually really separated... the controller often directly manipulates both the view and model. Restrictions such as not allowing the view to manipulate anything helps code to stay clean and intelligible.
When you have no structure or organization in a programming project it can be nearly impossible to avoid having huge routines which do a little bit of everything because there is really only one place in the code in which to build functionality upon. What this generates invariably is a tangled mass of spaghetti code that no language, no matter how high-level, can save you from. This creates code that just plain sucks because nobody else can understand it, and even you will be unable to understand it two weeks from the time it is written.

Collision detection, alternatives to "push out"

I'm moving a character (ellipsoid) around in my physics engine. The movement must be constrained by the static geometry, but should slide on the edges, so it won't be stuck.
My current approach is to move it a little and then push it back out of the geometry. It seems to work, but I think it's mostly because of luck. I fear there must be some corner cases where this method will go haywire. For example a sharp corner where two walls keeps pushing the character into each other.
How would a "state of the art" game engine solve this?
Consider using a 3rd party physics library such as Chipmunk-physics or Box2D. When it comes to game physics, anything beyond the most basic stuff can be quite complex, and there's no need to reinvent the wheel.
Usually the problem you mention is solved by determining the amount of overlap, contact points and surface normals (e.g., by using separating-axis theorem). Then impulses are calculated and applied, which change object velocities, so that in the next iteration the objects are moved apart in a physically realistic way.
I have not developed a state of the art game engine, but I once wrote a racing game where collision was simply handled by reversing the simulation time and calculate where the edge was crossed. Then the car was allowed to bounce back into the game field. The penalty was that the controls was disabled until the car stopped.
So my suggestion is that you run your physics engine to calculate exactly where the edge is hit (it might need some non-linear equation solving approach), then you change your velocity vector to either bounce off or follow the edge.
In the case of protecting against corner cases, one could always keep a history of the last valid position within the game and state of the physics engine. If the game gets stuck, the simulation can be restarted from that point but with a different condition (say by adding some randomization to the internal parameters).

What is the best approach to compute efficiently the first intersection between a viewing ray and a set of objects?

For instance:
An approach to compute efficiently the first intersection between a viewing ray and a set of three objects: one sphere, one cone and one cylinder (other 3D primitives).
What you're looking for is a spatial partitioning scheme. There are a lot of options for dealing with this, and lots of research spent in this area as well. A good read would be Christer Ericsson's Real-Time Collision Detection.
One easy approach covered in that book would be to define a grid, assign all objects to all cells it intersects, and walk along the grid cells intersecting the line, front to back, intersecting with each object associated with that grid cell. Keep in mind that an object might be associated with more grid-cells, so the intersection point computed might actually not be in the current cell, but actually later on.
The next question would be how you define that grid. Unfortunately, there's no one good answer, and you need to consider what approach might fit your scenario best.
Other partitioning schemes of interest are different tree structures, such as kd-, Oct- and BSP-trees. You could even consider using trees combined with a grid.
EDIT
As pointed out, if your set is actually these three objects, you're definately better of just intersecting each one, and just pick the earliest one. If you're looking for ray-sphere, ray-cylinder, etc, intersection tests, these are not really hard and a quick google should supply all the math you might possibly need. :)
"computationally efficient" depends on how large the set is.
For a trivial set of three, just test each of them in turn, it's really not worth trying to optimise.
For larger sets, look at data structures which divide space (e.g. KD-Trees). Whole chapters (and indeed whole books) are dedicated to this problem. My favourite reference book is An Introduction to Ray Tracing (ed. Andrew. S. Glassner)
Alternatively, if I've misread your question and you're actually asking for algorithms for ray-object intersections for specific types of object, see the same book!
Well, it depends on what you're really trying to do. If you'd like to produce a solution that is correct for almost every pixel in a simple scene, an extremely quick method is to pre-calculate "what's in front" for each pixel by pre-rendering all of the objects with a unique identifying color into a background item buffer using scan conversion (aka the z-buffer). This is sometimes referred to as an item buffer.
Using that pre-computation, you then know what will be visible for almost all rays that you'll be shooting into the scene. As a result, your ray-environment intersection problem is greatly simplified: each ray hits one specific object.
When I was doing this many years ago, I was producing real-time raytraced images of admittedly simple scenes. I haven't revisited that code in quite a while but I suspect that with modern compilers and graphics hardware, performance would be orders of magnitude better than I was seeing then.
PS: I first read about the item buffer idea when I was doing my literature search in the early 90s. I originally found it mentioned in (I believe) an ACM paper from the late 70s. Sadly, I don't have the source reference available but, in short, it's a very old idea and one that works really well on scan conversion hardware.
I assume you have a ray d = (dx,dy,dz), starting at o = (ox,oy,oz) and you are finding the parameter t such that the point of intersection p = o+d*t. (Like this page, which describes ray-plane intersection using P2-P1 for d, P1 for o and u for t)
The first question I would ask is "Do these objects intersect"?
If not then you can cheat a little and check for ray collisions in order. Since you have three objects that may or may not move per frame it pays to pre-calculate their distance from the camera (e.g. from their centre points). Test against each object in turn, by distance from the camera, from smallest to largest. Although the empty space is the most expensive part of the render now, this is more effective than just testing against all three and taking a minimum value. If your image is high res then this is especially efficient since you amortise the cost across the number of pixels.
Otherwise, test against all three and take a minimum value...
In other situations you may want to make a hybrid of the two methods. If you can test two of the objects in order then do so (e.g. a sphere and a cube moving down a cylindrical tunnel), but test the third and take a minimum value to find the final object.

Resources