text:
# How to explain the co-existence of peace and violence in religion

If you look at religions in world history they are often a source of conflict.

Disclaimer: Obviously this is not true of all religions nor is it a judgement on those religions for which it was or is true.

Now, with that disclaimer in place, what is it about religion that can make it a vehicle for violence?

With a few exceptions religious dogma generally preaches peace, and in the end people are the source of violence. But far too often religious belief is used to promote violence.

What views, teachings, beliefs or rules allow this contradiction; preaching peace and promoting violent conflict? Or is it something completely unrelated to the religion at all?

For a frame of reference this is the world in which this religion will exist, as well as some of my goals for the religion itself.

• There is a pantheon of gods, sort of Greek styled, but only one is worshiped as part of this religion as she was the only one responsible for creating the world.
• The formal modern organized incarnation of the religion developed after a massive map altering conflict between two racial factions came to a climax (that being the map altering devastation).
• Framework can be related to what the Catholic church and its militant orders were in the middle ages/crusade eras. Meaning there are few other central powers and the church manages land, banking and wealth in general.
• At times it will be an expansionist religion not unlike Christianity during the crusades.
• Nicely sandboxed ;) Jan 6 '15 at 15:01
• A parent will teach their child to be nice to people. They will also often teach their child self defence. Perhaps religion, like parents, is simply accepting the world as it is: a place where we hope for peace but accept violence exist and is, occasionally, necessary to prevent greater evil. Jan 6 '15 at 17:10
• @JonStory I would like to believe that you are right on that but history tends to tell a different story, and actually, preventing evil is an argument often used...which is convenient when you define what evil is. Jan 6 '15 at 17:12
• I thought this was a good question until I've seen what kinds of answers it invites. Many are just general rants about religion without attempting to answer the question, and the votes on the answers don't seem to represent how well they answer the question, but whether the voters are for or against religion in general.
– vsz
Jan 7 '15 at 19:10
• @vsz I quite agree but I think the answer is to use down votes, not restrict questions of this type. Jan 7 '15 at 19:24

What views, teachings, beliefs or rules allow this contradiction; preaching peace and promoting violent conflict? Or is it something completely unrelated to the religion at all?

People naturally believe different things, but most religions dictate what a person is allowed to believe, via a sacred text or creed. I was raised Catholic, (now non-practicing), and part of mass ceremony is a literal vocalisation of what we all "believe" (the Nicene Creed)

This conformity of belief can railroad religious followers' thought processes and make them more susceptible to doing the bidding of religious leaders "in the name of religion", and less likely to question those actions.

Religion has often provided the pretext for violence, but the underlying causes of that violence are rarely religious, and often more to do with power and greed. History is full of examples (both distant and recent) of people using religion as an excuse to get one over on neighbours. Even right now, the current situation in Iraq and Syria can be seen to be more to do with filling the power vacuum than religion.

However, as KSmarts pointed out in the comments below, religion alone is not the only thing that produces this "conformity of belief". There are many things in human culture that can set people against each other, besides religion. Political Allegiance and Race are among the more serious ones. The conflict in the North of Ireland is often seen from the outside as Catholics vs. Protestants, a religious conflict. In fact, it's more a case of Unionists (those who believe the north should be part of the United Kingdom) and Nationalists (who believe it should be part of the Republic of Ireland). There are Catholic Unionists and Protestant Nationalists, although both are rare. However during the height of the troubles, lots of innocent people were targeted simply because they were Protestant or Catholic.

If we take a step back and look at it, what really causes violence is perceived difference, which probably harks all the way back to our simian ancestry, where rival groups of primates would fight for dominance.

So to sum up my rather confusing and thrice edited answer, I believe that the human tendency toward violence is unrelated to religion. It can certainly be exacerbated by the actions of religious leaders, but this is not unique to religion.

NOTE: Thanks for all the upvotes! I've edited this answer so many times it bears little resemblance to what you all voted for, but I hope it's still agreeable. Thanks for KSmarts for pointing out the contradictions in my original answer

• I tend to agree with you but I am wondering if there are certain aspects of belief systems, or maybe the way religions codify beliefs that makes this a pretty common problem. Jan 6 '15 at 15:14
• I think religion itself is the problem, not specific belief systems. I've thought about it some more. see updated answer. Jan 6 '15 at 16:37
• Many historians argue that these were more of an expansion attempt by western christendom than a true holy crusade. Which scholars argue that? As I understand it, the Crusades--particularly the earlier ones--were an attempt by "Western Christendom" (aka. what was left of Christendom after Islamic invaders overran Eastern Christendom) to restore territory that had been overrun by Islamic invaders. Jan 6 '15 at 22:08
• I'm not a historian and I don't have any sources on that, so I've struck out that entire paragraph Jan 7 '15 at 9:12
• So, it is unrelated to religion, but religion itself is the problem? That doesn't seem consistent. Also, the "conformity of belief" leading to hostility is hardly exclusive to religion. For example, there's politics. There's even more trivial examples, too, like how to format computer code, the importance of Ewoks in Star Wars, or the use of Oxford commas. (Yes, I deliberately included three examples just to use an Oxford comma) Jan 7 '15 at 17:36

Disclaimer: As with the question, this answer is not intended to cause offence. I have endeavoured to be reasonably neutral but any offence caused is unintentional.

There are several reasons that religions can be sources of conflict. One of them is the main power why violence occurs in any context - I'll try to explain some.

## People

People are the number one factor causing war. People are essentially different and hold different points of view, which causes disagreement. Although at a national level we can try to resolve our differences peacefully, this doesn't always work, and at the individual level by far the easiest way to deal with it is to shoot your adversary. Job done. However, other factors do also play a part:

## Scriptures

Almost all religions have scriptures. Christianity the Bible, Islam the Qu'ran (Koran), etc. Since these scriptures were supposedly written at the time the religion was young, they are often taken to be the Word of God (please, substitute God for any name you use). This gives people reason to believe them: they are the representations of the views of the highest being in existence and thus should be followed. Some people take this to the extreme that since they are from the highest being, they are above mere human justice systems; thus, if there is a suggestion that killing others is the right thing to do, some people are willing to do so.

## Other People

People take great amounts of influence from the behaviour and teaching of others they respect. Religious leaders such as priests, rabbis, and imams have huge amounts of respect from those they preach to. In many societies with some dissent, different leaders preach different points of view, which leads to groups of religious people angry at each other. Alternatively, leaders of different religions preach opposite viewpoints, so different religions get angry at each other and are willing to take up arms in defence of their way of life.

For example, if a government is being particularly obnoxious in the Nofun province of Horriton on the world of Conflictada, a Permapees priest would preach that everyone should remain calm and use democratic process to oust the government, while a Kildemal priest would tell his community to go and launch rockets at the government buildings and take over. This gives the Permapeesans reason to tell the Kildemalans that they're wrong; this enrages the Kildemalans and causes fights; fights escalate; a Permapeesan is shot; his community retaliate with grenades; the Kildemalans launch missiles which causes the Permapeesans to bomb them; everyone hates each other, kills each other, bullets fly and start killing everyone more people get involved more points of view more guns more bullets more death atomic bombs oh no auntie Edith why help us where is God now. Oh. Welcome to World War One.

• "Since these scriptures were supposedly written at the time the religion was young, they are often taken to be the Word of God" Doesn't seem to be true for the Christian Bible, and I suspect the same for Muslim and Jewish Faiths. Jan 9 '15 at 9:57

A complicated issue. One that I can best describe looking at history.

Historically, long periods of conflict that have been blamed on religion (even the crusades) had a tangle of interrelated causes--most notably in the case of the Crusades--the economic decline of the Western Roman Empire. You ultimately had a shrinking tax base with no real positive inflow to the economy. A large part of Rome's wealth was really derived by tax payments from the Eastern Empire, and the split into two empires set the stage for the complete financial collapse of the Western Empire. When you couple this with urbanization and plantation farming AND Rome's welfare system (Citizens were freely given doles of grain) you had a large population of destitute people, not enough food or gold coming in, and because you have no money--you couldn't just go and conquer a rich neighbor, because let's face it, by that point in time--there weren't really any rich neighbors... except for those lands captured by "the false prophet Mohammad..."

[Clarification: The Western Roman Empire, after losing the tax base from the east had to find another way to support itself, and in truth--at that time, if you wanted wealth you'd go conquer it. Well, the rich parts of Europe had already been taken. Here's a map of the empire after the split.

It couldn't support the territory it already owned. All the red on the map would fracture, and eventually all of northern Africa, the area known as the middle east, and most of Turkey would all eventually come under Muslim rule. At that point, it would become possible "reconquer" these lands. My original statement attempted to condense several hundred years and in the process apparently made me state an impossibility.]

Its important to note here that with the advent of Roman Catholicism, the Church offered itself as a competitor to Lords and Emporers which is the main reason why it ended up being institutionalized into the structure of the state in most cases. (Eventually culminating in the idea of "Divine Right," which was a balance of power between the ruling class and the Church.) I've glossed over a ton of nuance here, but here's some bullet-points:

• Religion is sometimes used by power-seekers to influence members of state, when the religion itself has sway over a large group of people
• Members of state often seek sanction for acts by religious authorities--this again, depends entirely on power dynamics.
• Religions tend to address the needs of everyday people--if the state is a particularly bad one, this can lead to a revolution "sanctioned by God."
• Economic factors for both everyday people and the ruling class tend to be the primary motivation for war.
• Religion can be used by the state to pacify its populace. ("Religion is the opiate of the masses.")
• Religions nearly all tend to viewing human beings as flawed or fallen beings that require "fixing" by some form of worship/path/ritual(s). This is less true of Pagan religions that tend to accept man's mercurial nature as-is. Keep this fact in mind while creating your religion.

So to summarize, while greed and power certainly play a role in violence, far greater is the factor of economics in setting the mood of a people and their willingness to be swayed by greedy people wielding power wishing to conquer. Religion is generally a psychological multiplier, playing to our tribal instincts in subtle ways--historically, at the whim of those who wield power over us. You need to carefully consider the political balance of power in your world so that the "right" dynamic is in place to capture the feeling and mood you want. Is your religion in tension with the state(s) in which it resides? Is it in conflict with the people? (The state or a prophet could implement a new religion in this case.)

• I hadn't really been thinking about the internal domestic aspects of religious violence, that's a good point. Jan 7 '15 at 17:16
• Err... The generally accepted date for the fall of the Western Empire is 476 CE (en.wikipedia.org/wiki/Fall_of_the_Western_Roman_Empire ), but Mohammed didn't create Islam until (ca) 722 CE. So, given the century and a half gap, it seems hard to understand how the Western Romans possibly could have attacked lands captured by Islam. And for the Eastern/Byzantine Empire, the Islamic lands in question had recently been captured, or were in the process of being captured, from them. Jan 7 '15 at 20:00
• @jamesqf Not quite sure how you're reading my post as "Western Roman Empire decides to attack Islamic Sultans." The OP gave the crusades context, and my part was to paint--in broad strokes--the economic history that defined the "dark ages," and penultimately led to the crusades. Jan 8 '15 at 12:59
• @avgvstvs: I'm reading your first paragraph, where you describe the split between Eastern & Western Roman Empires, Rome's welfare system, finiancial collapse of the Western Empire leaving it no option but to attack Islamic lands, &c. I just don't see how that's a) possible, given that the Western empire ceased to exist 150 years before Islam; and b) economic conditions among the successors half a millenium later had virtually nothing to do with Rome. Bottom line is that your exposition at best can easily be read wrongly. Jan 8 '15 at 18:59
• @jamesqf I edited the post to hopefully clarify. Jan 9 '15 at 12:53

In my opinion 3 things brings religion and violence together.

1. Greed: Greedy people use religion to convince others to commit violence against "heathens and apostates" in order to take what was theirs.

2. Power: (very closely related to Greed). Use the power to collect more power by taking lands and life of those who dare defy the 'truth'.

3. Fanaticism: Believing you are right to such a degree that any who disagree are a threat and they must be convinced to change their ways, by violence and death if need be.

Often those greedy or power hungry find Fanatics to lead and do their dirty work for them. There was nothing in the bible that encouraged the Crusades, it was all human Greed and need for power over more people that brought out the sword.

I think the first Crusade was somewhere between items 2 and 3, the rest of them that followed were mostly for #1.

Iran seems IMO to be mostly #2 and ISIS is definitely #3.

• It would surprise me if many within ISIS are not actually motivated by 1 and 2 at least as much as 3. Jan 6 '15 at 15:22
• @TimB I'm sure, and some are likely motivated by fear of what would happen if they spoke out about what they believe... Jan 6 '15 at 15:28

It seems to me, from my observations of the world and critical introspection, that aggression and violence arise from insecurity. It does not take much to see this in people, and I think most people who can be honest with themselves know that when they strike out, it is because they do not feel secure; it is because they are afraid.

Faith is a required for religions because they inherently do not deal in the realm of evidence based science. Religion is a practice of the supernatural and conviction, rather than the natural world and the humbling practice of scientific discovery.

The universal truth offered by religion does not reach man's heart of hearts. People do not believe that sin hurts God in the same way they believe they will fall from a bridge if they step over the edge. We know in our heart of hearts that gravity is there, even if we can't see it or completely understand what it is, we know it is there. But people do not have the same reassurance about a God or gods, so belief in them requires faith. Faith is inherently insecure; by definition, it is not knowledge.

I notice that a lot of people have made disclaimers so as not to hurt anyone's feelings here. Would they do that same thing if they were about to talk about gravity? Obviously not, the reason is that people's faith is an insecurity for them. If one questions a person's belief that they will fall if they step off of a bridge they do not get upset, because it is not an insecurity for them.

Religion simply provides a massive conduit for insecurity; it says "here is a universal truth, doom to unbelievers" and man can only pretend he believes, but in his heart of hearts, usually not consciously, he knows he doesn't truly believe.

If you question faith, people's feelings get hurt; they get defensive; they get angry. If a large group of insecure people get together, violence is bound to happen. Whether it's under the direction of an insecure leader or simply the will of the mob, it's insecure humans that create violence.

Now put two of these groups near each other, both trying to convince themselves of their own conviction while seeing the abhorrent contradiction of opposing universal truths, and it's not surprising to see sectarian violence.

So, while I agree that religion is not the cause of violence, I think that it is inherently flawed. The best we can do is agree that there is a very tiny set of things that we know, the rest is an ongoing investigation. The best test, in my view: if questions make someone uncomfortable about what they claim is the truth, then they don't, in their heart of hearts, believe it to be truth.

• Very well written Jan 6 '15 at 19:22
• Re "People do not believe that sin hurts God...": But the concept of sin is (AFAIK, anyway) really only a property of Judeo-Christian religions. In Islam, it seems more like a slave's disobedience to his master's commands; Buddhism & Hinduism have the idea of karma, which is much closer to gravity (that is, it is an inevitable consequence rather than the gods' displeasure); other religions seem to be driven more by honor & shame. How, for instance, would sin relate to warriors fallen in battle feasting in Valhalla, vs the shame of dying in bed - a "straw death". Jan 7 '15 at 4:53
• There is a good chance that the Sunk Cost Fallacy is also involved here. If you spend 30 years believing something and are then confronted with conflicting information it becomes very easy to say "I have spent 30 years believing this, so it must be true, because I don't want to feel I spent 30 years being wrong." and if both sides do this, with the same justification, then the only thing that can remain between them is conflict.
– Erik
Jan 7 '15 at 9:59
• This is less an answer and more a general rant about religion, with a hefty dose of sampling bias. Countries don't (and didn't) declare war on each other because of the insecurities of the general population. Wars arise when people in power try to increase or maintain their power. They can just as easily abuse religion as they can abuse more liberal views, as either pretexts for war or for motivating their own people.
– vsz
Jan 7 '15 at 19:01
• @vsz It appears you didn't read the answer in its entirety, because you're disagreeing with a statement I didn't make. Namely, I didn't talk about governments or why they make war. Besides, I made the point that the violence can be "under the direction of an insecure leader", which can be a leader insecure about their current level of power or the loss of it. You might scale that to a government leader, and it appears you have, but I didn't specifically do so. What do you actually disagree with that I stated? And, is your offence based on your own religious views? Jan 7 '15 at 19:36

There are several main sources of this contradiction

Us vs. them: Many religions promote peace within the religion while providing less of a framework for peace outside of the religion. Even if they promote peace everywhere, it is not uncommon for a religion to turn a blind eye to violence which appears to promote its desires.

Us vs. us: It is very rare for everyone in a religion to interpret the book in the same way. Sometimes violence will simply happen in the resolution

Them vs. us: Generally speaking, a religion will not survive if it is so peace-oriented that it cannot keep up with a violent adversary because its people will be killed off, ending the religion.

Shortsightedness: Even if a religion is mathematically perfect, its worshipers are not. It is easy for a worshiper to get caught up in a short term goal which makes violence appear acceptable.

This is easy to understand when you look at religion from the perspective of its fundamental intent: to improve human relations and understanding of oneself in relation to others.

Like government, religion sets out boundaries on behavior. While the specifics may differ, they all share the fundamental intended goal of attempting to improve humanity. They even call their guidelines "laws" in some cases.

This is where the human factor comes to play. Adherents of philosophies of religion and government believe their version to be the most true and seek to change the minds of others. When those adherents begin to wrap those philosophical ideas around their identity, any challenge becomes blasphemous- an affront to their deity or personal philosophies. Inevitably, they blame the blasphemous for the world's ills and seek to change them through debate. If debate isn't enough then sometimes they resort to force/violence.

Religion can't hurt anyone. People, on the other hand, turn the words of their religion/government into vehicles for violence or peace. The individual is responsible for choosing violence against their fellow man, not the religion.

One note: The reason I'm including government with religion is that too many forget that government seeks to do the exact same thing- behavior control. In recent history though, few governments tie itself to the divine as it once did yet have been just as violent, and in many cases, more so than in some religions. Some governments were no different than the religion like those who claimed "divine" rule in the past. This explains the violence against dissidents or non-violent, yet "immoral" behaviors that government and religion share.

Breaking the rules is breaking the rules in both cases and the people who believe in either philosophy have the power to wield violence against their fellow man for breaking those rules and/or share in peace between those who follow those rules.

• Welcome to the site. Excellent first post. Jan 7 '15 at 18:40

I'm going to go off on a different direction than everyone else:

## This dichotomy has nothing to do with religion.

Instead, consider that humans (taken as a whole) are extremely xenophobic. Literally: "an irrational or unreasoned fear of the foreign or unknown". You can see examples of this throughout history - any time a culture meets another, each consider themselves superior and disparage each other, sometimes over the smallest differences. This could range from the large-scale (European explorers vs the Chinese empire, Cold War) to the neighborhood ("Oh, you don't want to live there! That's where all the snobs/junkies live."), to the trivial (OS wars). There have been studies which show that other primates can behave similarly, so this behavior has been with is a long time.

The only way to overcome this inherent xenophobia is to expand the definition of what is "inside" your group, so that there is less that's foreign. If a person with brown/yellow/purple skin isn't part of your group, you will look down on them. If your group is expansive enough to acknowledge that they're equally human, then you have no issues with them.

So, too, with religion.

Religion, regardless of its message, cultural value, or other positive characteristics, is a differentiator. If someone follows a different god than you, they're different. If someone follows the same god differently, they're different. If someone follows the same god, in the same way, but more or less actively than you, they're different. These are all degrees of the same thing, and the smaller the difference the easier it is to include them (and thus not have an issue with them), but it still comes down to "us vs them".

• Do you suppose then, that people of one color will fly planes into buildings full of people mostly of another color? Or is that something uniquely allowed by religion? Jan 9 '15 at 15:08
• @Samuel - Planes specifically? Probably not. But there's constant violence related to color. But 9/11 wasn't about religion either - the attackers happened to be Muslim, but it was a politically motivated attack on America, not a religiously motivated attack on Christianity. Otherwise they would have flown planes into the Vatican. Jan 9 '15 at 15:30
• So there was a political party somewhere promising some kind of afterlife reward? I think not. Religion enabled such an attack. I'm not claiming religion is the only source of violence, far from it, but it certainly has enabled incomprehensible levels of violence. Specifically those that promise some form of consciousness after death. Jan 9 '15 at 16:52
• @Samuel - Every major religion promises something after death, whether it be Heaven, Hell, Hades, Paradise, a new reincarnated life, resurrection in your own (or new) body, Nirvana, The Summerlands, continued existence as a ghost, the Great Pasta Bowl, or simply "It's there, but we can't know anything about it". Suicide attacks are nothing unique to religions: see the origins of the term "Banzai" for a cultural example. I'm not saying people don't justify slaughter through their religions, just that any difference could serve the same role Jan 9 '15 at 18:11
• Seppuku, or Banzai, is enabled by a promise of something after death, honor. Just because something is not done in the name of a religion, does not mean religion had no influence on the act. Any difference could indeed be a cause for violence, I don't disagree. Jan 9 '15 at 19:04

Belief businesses of all kinds, including religions, governments and even programming-language advocates, grow their customer base by distributing absolute truths. These truths are, by design, intense, exclusive and non-cooperative. They have to be, or they wouldn't be able to wrestle potential customers out of the clutches of the competition. There is little or no value in consumers who serve two or more brands. No belief can flourish if it allows alternatives to survive. Absolutism is job one, fanaticism the only goal.

At the top of each great faith fortress, learned scholars pontificate their unique creeds, eloquently proclaiming the superiority of their side over all others. From ivory towers, they scream at each other, as the masses watch from below.

Down in the trenches, less learned believers dream of being great evangelists, teachers and fishers of men. Lacking their leaders' arsenal of words, lacking the bait of beautiful ideas, many turn to less loquacious methods of persuasion. Where reason fails, violence flourishes. Kill 'em all... and let the Gods sort them out!

What does "peace and violence" refer to here? - this needs to be understood correctly.

Religions usually promote mercy and compassion; however, all of them prescribe laws to deal with those that pose a threat to the society. For the greater good, they prescribe laws to kill those who inflict harm on society. This is still inline with mercy and compassion for the society as a whole. If religion does not do this, then society will suffer!

Similarly, a religion does not say "Cause war", but, for example, says that oppression is worse than killing, and for the greater good of humanity permits war under certain circumstances - and in some cases quite rightly projects it as a morally high thing to do.

We as humans get stuck on little things and do not always see the bigger picture. Ultimately, morals are nothing more than social constructs. We like to create slaughter houses for other animals but consider ourselves to be above them all and more superior.

It is naïve to say that there is a paradox. Apparently there is, but there is a bigger picture that needs to be understood.

• Answering this question is not simple as many different religions exist on earth and they vary a lot in their teachings. This as best as I can answer it while realizing that even traditions that may preach near pacificism and "non-violence" will not teach that a person not pick up weapons if they are on verge of extinction by being under attack by another people. This is a fact. Also I am looking at religions on their own and now confusin them with their followers here. Jan 7 '15 at 1:32

I'm surprised nobody mentioned Bishamonten

Bishamon is the Japanese Buddhist God of War, and the famous Uesugi Kenshin is one of their followers. Kenshin himself is legendary for his prowess in battle and his sense of honor, willing to kill his enemies' soldiers but not the innocent civilians

This is one of the core tenets in today's world: only those prepared to fight can protect peace. Use this to explain why some religious practitioners are violent: they are violent so the innocents don't have to be.

For an easier way of picturing this seemingly contradictory concept, take a look at Islam: Muslims generally preach peace, but their holy book specifically points out that heathens that threaten them should be fought against, either with pen or with swords. History suggests the latter is much more commonly used

Of course, this all assumes that all the practitioners put the need of many above their own, and are totally not using religion merely to gain loyal followers and later twist the interpretation of holy books to match whatever it is they're going to do Nostradamus interpretation style.

Religion tend to be formed when technological and scientific advances were not that much, and when technology improves what the holy books once said (that applies to their world) usually don't mention anything about the future world.

For example, none of the Holy books of the major religions ever mention anything about Internet porn or phone sex, so interpretations had to done and assumptions had to be made to deal with those religiously. This allows one to use wild imaginations and interpretations to justify their violence

The top priorities of any religion are to preserve, protect and propagate itself. Violence and other coercive methods happen to be tried-and-true means to each of these ends.

• Self-preservation: By this I mean the prevention of new ideas and customs that might degrade the integrity of the religion from taking hold. Islamist factions such as ISIS and Boko Haram are particularly notorious for using violence as a means of preserving what they hold up as the Muslim faith in its original, pristine form. They not only routinely impose draconian punishments for violations of Islamic laws and principles, but consider any attempt to reform or relax those laws as tantamount to apostasy (i.e. abandoning Islam outright) and therefore punishable by death. (Indeed, the very name Boko Haram translates to English as "Western-style education is sin", a pointed reference to the self-preservation imperative.)
• Self-protection: By this I mean the defense of the faith and its community of adherents from outside threats. While violence in self-defense may be considered justifiable on its face, religions (and indeed structured ideologies of all sorts) are all too often prone to paranoia, sensing existential threats to the faith that are either nonexistent or overblown. Whenever, for example, Islamists characterize Western measures against terrorism as an attack on all of Islam, and then call for violent jihad to oppose these measures, they are appealing to this self-protection imperative.
• Self-propagation: By this I mean ensuring that the faith will endure in perpetuity, which means continuously replenishing its flock of adherents via procreation and/or conversion of nonbelievers. In this context, violence is usually done to serve the latter purpose (i.e. intimidate people into converting by making examples of those who refuse, ISIS again being a prime recent example), though it could also be understood to include coercive laws and policies designed to ensure that followers have many offspring and raise them all under the faith.

Note: All of my points above cite Islamists as examples of religious violence. This is not to single out Islam as having a monopoly on religious violence, merely to provide recognizable examples from recent events.

It is unrelated to religion.

The problem is that mankind has a tendency to use/bend/exploit peaceful teachings as a rationalization for violence.

Contradictory scriptures makes the matter worse "eye for an eye", "thou shall not kill", "love thy neighbor". Demagogues can exploit this ambiguity to suit their needs

Consider religion being used by slaveholders

http://religion.blogs.cnn.com/2011/04/12/how-the-bible-was-used-to-justify-slavery-abolitionism/

Brinton, author of “Balancing Acts: Obligation, Liberation and Contemporary Christian Conflicts,” says both the Union and the Confederacy invoked the Bible to justify their positions on slavery.

Slaveholders justified the practice by citing the Bible, Brinton says.

They asked who could question the Word of God when it said, "slaves, obey your earthly masters with fear and trembling" (Ephesians 6:5), or "tell slaves to be submissive to their masters and to give satisfaction in every respect" (Titus 2:9).

Christian opponents of slavery elevated biblical principles of justice and equality above individual passages that approved exclusion, Brinton says.

Mankind has the exact same tendency with it's laws. Interpreting and bending laws so people can rationalize violence.

Also worth considering that religion has a wide audience and is often used as a vehicle for propaganda.

Also consider the Etymology of the word propaganda

http://en.wikipedia.org/wiki/Propaganda

Propaganda is a modern Latin word, the gerund form of propagare, meaning to spread or to propagate, thus propaganda means that which is to be propagated.[1] Originally this word derived from a new administrative body of the Catholic Church (congregation) created in 1622, called the Congregatio de Propaganda Fide (Congregation for Propagating the Faith), or informally simply Propaganda.[2][3] Its activity was aimed at "propagating" the Catholic faith in non-Catholic countries.[2]

From the 1790s, the term began being used also for propaganda in secular activities.[2] The term began taking a pejorative connotation in the mid-19th century, when it was used in the political sphere.[2]

It is not the fault of religion. It is a flaw in human character. Demagogues know how strong this power is, you can promote violence and give it divine blessing in the process.

http://en.wikipedia.org/wiki/Christianity_and_violence

Miroslav Volf says that his religion, Christianity, is intrinsically nonviolent, but has suffered from a "confusion of loyalties". He proposes that "rather than the character of the Christian faith itself, a better explanation of why Christian churches are either impotent in the face of violent conflicts or actively participate in them derives from the proclivities of its adherents which are at odds with the character of the Christian faith." He believes that "(although) explicitly giving ultimate allegiance to the Gospel of Jesus Christ, many Christians in fact seem to have an overriding commitment to their respective cultures and ethnic groups."[12]

A careful reading of the Book of Ecclesiastes sheds insight on this question. The book systematically attacks many reductionist fallacies present in human belief systems. It calls into question: the ability of moral living to protect you from harm, the reward of diligent labor, the fairness of human justice, happiness through sexual gratification, madness, religious piety, the value of wisdom, leaving your estate to unworthy children, etc. Taken together with the Book of Proverbs, you have the latter saying that if you follow certain rules, life will go well, while the former says that even if you follow the rules, bad things happen to good people (a point driven home even more so in Job).

Most (maybe all) systems of thought, whether religious or scientific, are reductionist in some way. They simplify and gloss over points, maybe even gross failings that their ideas do not address. When these systems fail, people are left hurt, angry, confused. This situation makes society ripe for people urging stricter adherence to the rules (on pain of death or punishment) or abandoning the accepted order for a new religion or belief. Since a thing and its opposite cannot both be true, one of those beliefs is teaching falsehood, undermining community life and the state. It must be eliminated.

Only rare circumstances will lead to peaceful relations between people of different faiths:

(1) Exhaustion. Europe fought religious wars for centuries. Eventually the death toll was too great, and kings mandated tolerance in order to save their kingdoms from perpetual civil war.

(2) Pacifism. Some faiths strongly oppose violence.

(3) Slavery. Some faiths kill or enslave all their opponents.

(4) Benevolent dictators. Ghengis Khan chose no religion for himself and prevented any one faith from being made the state religion, to preserve peace in the empire.

The words of Jeremiah are instructive: "You will seek me and find me when you seek me with all your heart." This is a call for the individual pursuit of spiritual knowledge, something incompatible with formal systems. To the extent that a religion is an expression of community laws and regulations for living, it is necessarily incomplete and reductionist, hence potentially dangerous. When it fosters the individual pursuit of divine knowledge, wherein God meets both the common and peculiar needs of each person, then it can be a positive force.

To be complete, there is another force beside our imperfect nature that turns religion into a tool of violence and evil. I believe that the devil exists, and uses lies and murder to turn people against each other. Of all my beliefs, this is one I would be happiest to be shown to be wrong. However, M. Scott Peck's book People of the Lie persuaded me many years ago and I have yet to find any evidence to contradict it.

I think your view of religion is perhaps a bit limited, particularly in regards to "With a few exceptions religious dogma generally preaches peace..." There are plenty of historic religions that didn't - Greek/Roman, Norse, Aztec, &c - and I think the same might be said of Hinduism & Shinto today. There are also examples, such as Christianity & Islam, which preach peace towards fellow believers, but are all in favor of violence towards infidels and heretics. So if your scripture tells you it's ok to kill off the non-chosen people (lots of Old Testament examples), or to "...kill the unbelievers wherever you find them, and capture them and besiege them, and prepare for them each and every ambush" (Quran 9.5), then if you are a believer, that is what you do.

• This should probably be commentary under the op rather than an answer. Thanks for the feedback though. Jan 6 '15 at 19:44
• @James: It would have been, if I hadn't originally intended it to be rather longer and have paragraphs. But I decided it was better not to get into issues like whether the Crusades were Christian expansionism, or resistance to Islamic expansionism. Jan 6 '15 at 21:57
• I think it's valid for answers to address assumptions in the question, it would be nice to see some more of the question addressed as well though. Jan 6 '15 at 22:20
• Roman Religion didn't promote war per se. It wanted wars to be just ones, but it wasn't hard to find reasons when needed. Much Roman expansion was by peaceful means (inheritance), and inside the Empire the norm was peace. Jan 16 '15 at 17:17

Religion promotes faith. Unfortunately, faith conflicts with critical analysis and reason.

Religion, and spirituality, suggest that there is a "language of love" that stands above reason etc. which may or may not be true.

This set up, which prevents nihilism in an ideal scenario, can easily be derailed by someone looking to exploit people for personal gain.

Essentially, strong religious believes make people more susceptible to manipulation by others who establish themselves as lead figures within the tradition.

• I don't think faith requires a lack of critical analysis and reason. To be fair, it often does take that route but there have been religious scholars (Aquinas for example) that worked to bring faith and science into sync. Jan 12 '15 at 20:28
• I've attended cult meetings. They employ practices (singing the same words for hours, isolation from family or friends, use of confessions to instill guilt, etc) that break down the will, like brainwashing. Such groups do war against reason. They are destructive. I have also attended religious meetings that are not at all like this. An example from Math is useful. Lobachevsky turned Mathematics on its head: he assumed parallel lines meet. He changed his axioms and got hyperbolic geometry. Euclidean and Hyperbolic geometry - both logical, but logic can't prove the axioms. Religions have axioms. Apr 10 '15 at 14:51

It's Easy:

If religion (god belief) is the ultimate explanation, it's above critique, and easily becomes the ultimate justification. Or excuse.

Then the human motives below awareness creep in, and "Hey. . . I'm doing it all for god. Wouldn't want to stir up his anger. Like making a volcano blow off or a plague hit.."

Ya gotta believe!

I am deliberately on thin ice here, to show that it is not religion per se which which promotes violence, but people who use religion as pretext to gain power to themselves, when they see opportunity to do so

Differences between Christianity and Islam, as example of circumstances which may promote violence:

Origins

• Christianity emerged as the religion of the weak under oppression on Roman religion, so it took them more than 500 years to be established enough (converting Roman Empire to christianity) to start oppressing others (christianization of Eastern Europe, then Crusades and Inquisition).
• Islam emerged as religion of the powerful, of the military conquest, oppressing others nations/religions from very beginning (or, as suggested by commenter, 23 years after conception), and people joining Islam because it was on the more powerful side (unlike Chritianity, which started weaker).

Relations progress and new technologies

• Christianity plunged into Dark Ages quickly after Roman Empire disintegrated, and technological advanced few centuries later years enabled it to expand. Returning to origins means Dark Ages.
• Islam started expanding militarily and technologically (translating classic Roman, Greek manuscripts, many of which survived only in arabic translations) and developing own advanced science (algebra, spherical trigonometry to get direction to Mecca, medicine, all more advanced than contemporary Christian science). So for Islam, returning to origins are Golden Times.

Writing

• Roman alphabet/writing is easy to adapt to book press, and many rogue printers existed, printing dissenting religious literature (and unleashing centuries of religious wars, so people in Europe are better aware that religious fanaticism equals war).
• In Islam, professional writers invented copyright for translations, and opposed printing press (which is less convenient to arabic script). Printing in Arabic script was prohibited in Ottoman Empire from 1483 on penalty of death which likely influenced freedom of speech, press, and religious freedom.

Freedom of speech is majority being tolerant when minority expressing opinions majority disagrees with - and this post is perfect example how hard it is.

I have little knowledge about how other religions may influence civilization, sorry.

BTW I personally know many very peaceful Muslims, Hindus, Christians, Buddhists and atheists, and above is very generic extrapolation.

Also, monotheism would be IMHO more prone to violence, because existence of any other god is heresy (and converting such believers to one "true" god you are helping them to see "true" light). For polytheist, it is a matter to get support from a more powerful god from many to chose from (and so switching to "more powerful" monotheist god might be a rational decision).

Bottom line: it is not religion per se that promotes violence, but people, history, circumstances, opportunities.

Seems that believers of both sides got offended and downvoted my answer. Yet another example how religious faith and rational thinking does not mix. Both sides have disagreement debate in comments, and both downvote my answer. Which proves it is true.

• downvoters, care to explain why? Jan 7 '15 at 17:31
• I guess because it is a general rant about Christianity and Islam, with no attempt to answer the actual question. It also contains some factual inaccuracies, your abuse of the terms "dark ages" would make anyone interested in history dismiss your claims. It doesn't mean what you think it means.
– vsz
Jan 7 '15 at 19:07
• I was trying to show how similar ideas work differently in different circumstances. Well I guess it is very easy to become heretic if you don't follow prescribed thinking and try to think for yourself, and I have to live with consequences of my thinking. Jan 7 '15 at 19:18
• I think that this is not true: Islam emerged as religion of the powerful, of the military conquest, oppressing others nations/religions from very beginning. The Arabs where oppressed (kinda) by the Persian and Byzantine Empire. They rose and conquered old corrupted states. Not hard Persia felt almost without a fight and the Byzantine were weakened by wars and diseases. Jan 7 '15 at 20:00
• Islam was was conquering neighbors militarily during first few centuries. Christians were under Roman rule for first few centuries, being "fed to the lions" and not doing any military conquest. Jan 7 '15 at 20:07


text:
# 7 Spatial Analysis

Spatial analysis provides an expansive analytical landscape with theoretical underpinnings dating to at least the 1950’s (), contributing to the development of geographic information systems as well as spatial tools in more statistically oriented programming environments like R. We won’t attempt to approach any thorough coverage of these methods, and we would refer the reader for more focused consideration using R-based methods to sources such as and .

In this chapter, we’ll continue working with spatial data, and explore spatial analysis methods. We’ll look at a selection of useful geospatial abstraction and analysis methods, what are also called geoprocessing tools in a GIS. The R Spatial world has grown in recent years to include an increasingly good array of tools. This chapter will focus on vector GIS methods, and here we don’t mean the same thing as the vector data objects in R nomenclature (Python’s pandas package which uses a similar data structure calls these “series” instead of vectors), but instead on feature geometries and their spatial relationships based on the coordinate referencing system.

## 7.1 Data frame operations

But before we get into those specifically spatial operations, it’s important to remember that feature data at least are also data frames, so we can use the methods we already know with them. For instance, we can look at properties of variables and then filter for features that meet a criterion, like all climate station points at greater than 2000 m elevation, or all above 38° N latitude. To be able to work with latitude as a variable, we’ll need to use remove=FALSE (the default is to remove them) to retain them when we use st_as_sf. In Appendix A7.1, you can see more of the exploratory work of how we chose our values.

Adding a basemap with maptiles: We’d like to have a basemap, so we’ll create one with the maptiles package (install if you don’t have it.) Warning: the get_tiles function goes online to get the basemap data, so if you don’t have a good internet connection or the site goes down, this may fail. We can then display the basemap with tm_rgb.

For temperature, we’ll reverse a RColorBrewer palette to show a reasonable color scheme by reversing its RdBu palette with rev (which took me a long time to figure out – color schemes are much more challenging than you might think because there are many highly varied uses of color.)

library(tmap); library(RColorBrewer); library(sf); library(tidyverse); library(maptiles); library(igisci)
tmap_mode("plot")
newname <- unique(str_sub(sierraFeb$STATION_NAME, 1, str_locate(sierraFeb$STATION_NAME, ",")-1))
sierraFeb2000 <- st_as_sf(bind_cols(sierraFeb,STATION=newname) %>%
dplyr::select(-STATION_NAME) %>%
filter(ELEVATION >= 2000, !is.na(TEMPERATURE)),
coords=c("LONGITUDE","LATITUDE"), crs=4326)
sierraBase <- get_tiles(sierraFeb2000)
tm_shape(sierraBase) + tm_rgb() +
tm_shape(sierraFeb2000) +
tm_symbols(col = "TEMPERATURE", midpoint=NA, palette=rev(brewer.pal(8,"RdBu"))) +
tm_text(text = "STATION", size=0.5, auto.placement=T, xmod=0.5, ymod=0.5) +
tm_graticules(lines=F)

Now let’s include LATITUDE. Let’s see what we get by filtering for both ELEVATION >= 2000 and LATITUDE >= 38:

sierraFeb %>%
filter(ELEVATION >= 2000 & LATITUDE >= 38)
## # A tibble: 1 x 7
##   STATION_NAME     COUNTY ELEVATION LATITUDE LONGITUDE PRECIPITATION TEMPERATURE
##   <chr>            <fct>      <dbl>    <dbl>     <dbl>         <dbl>       <dbl>
## 1 BODIE CALIFORNI~ Mono       2551.     38.2     -119.          39.6        -4.4

The only one left is Bodie. Maybe that’s why Bodie, a ghost town now, has such a reputation for being so friggin’ cold (at least for California). I’ve been snowed on there in summer.

### 7.1.1 Using grouped summaries, and filtering by a selection

We’ve been using February Sierra climate data for demonstrating various things, but this wasn’t the original form of the data downloaded, so let’s look at the original data and use some dplyr methods to restructure it, in this case to derive annual summaries. We’ll use the monthly normals to derive annual values.

We looked at the very useful group_by %>% summarize() process earlier. We’ll use this and a selection process to create an annual Sierra climate dataframe we can map and analyze. The California monthly normals were downloaded from the National Centers for Environmental Information at NOAA, where you can select desired parameters, monthly normals as frequency, and limit to one state.

First we’ll have a quick look at the data to see how it’s structured. These were downloaded as monthly normals for the State of California, as of 2010, so there are 12 months coded 201001:201012, with obviously the same ELEVATION, LATITUDE, and LONGITUDE, but monthly values for climate data like MLY-PRCP-NORMAL, etc.

head(read_csv(ex("sierra/908277.csv")),n=15)
## # A tibble: 15 x 11
##    STATION   STATION_NAME   ELEVATION LATITUDE LONGITUDE   DATE MLY-PRCP-NORMA~
##    <chr>     <chr>          <chr>     <chr>    <chr>      <dbl>            <dbl>
##  1 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201001            13.2
##  2 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201002            15.0
##  3 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201003            11.4
##  4 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201004             3.3
##  5 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201005             2.29
##  6 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201006             0.25
##  7 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201007            12.2
##  8 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201008            20.6
##  9 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201009            10.2
## 10 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201010             5.08
## 11 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201011             5.08
## 12 GHCND:US~ TWENTYNINE PA~ 602       34.12806 -116.036~ 201012            14.7
## 13 GHCND:US~ BUTTONWILLOW ~ 82        35.4047  -119.4731 201001            32.5
## 14 GHCND:US~ BUTTONWILLOW ~ 82        35.4047  -119.4731 201002            30.0
## 15 GHCND:US~ BUTTONWILLOW ~ 82        35.4047  -119.4731 201003            30.7
## # ... with 4 more variables: MLY-SNOW-NORMAL <dbl>, MLY-TAVG-NORMAL <dbl>,
## #   MLY-TMAX-NORMAL <dbl>, MLY-TMIN-NORMAL <dbl>

To get just the Sierra data, it seemed easiest to just provide a list of relevant county names to filter the counties, do a bit of field renaming, then read in a previously created selection of Sierra weather/climate stations.

sierraCounties <- st_make_valid(CA_counties) %>%
"Sierra","Tehama","Tulare","Tuolumne","Yuba"))
mutate(STATION = str_sub(STATION,7,str_length(STATION)))
sierraStations <- read_csv(ex("sierra/sierraStations.csv"))

To get annual values, we’ll want to use the stations as groups in a group_by %>% summarize process. For values that stay the same for a station (LONGITUDE, LATITUDE, ELEVATION), we’ll just use first() to get just one of the 12 identical monthly values. For values that vary monthly, we’ll sum() the monthly precipitations and get the mean() of monthly temperatures to get appropriate annual values. We’ll also use a right_join to keep only the stations that are in the Sierra. Have a look at this script to make sure you understand what it’s doing; it’s got several elements you’ve been introduced to before, and that you should understand. At the end, we’ll use st_as_sf to make sf data out of the data frame, and retain the LONGITUDE and LATITUDE variables in case we want to use them as separate variables.

sierraAnnual <- right_join(sierraStations,normals,by="STATION") %>%
filter(!is.na(STATION_NA)) %>%
dplyr::select(-STATION_NA) %>%
group_by(STATION_NAME) %>% summarize(LONGITUDE = first(LONGITUDE),
LATITUDE = first(LATITUDE),
ELEVATION = first(ELEVATION),
PRECIPITATION = sum(MLY-PRCP-NORMAL),
TEMPERATURE = mean(MLY-TAVG-NORMAL)) %>%
mutate(STATION_NAME = str_sub(STATION_NAME,1,str_length(STATION_NAME)-6)) %>%
filter(PRECIPITATION > 0) %>% filter(TEMPERATURE > -100) %>%
st_as_sf(coords = c("LONGITUDE", "LATITUDE"), crs=4326, remove=F)
ggplot() +
geom_sf(data=CA_counties, aes(), fill="gray") +
geom_sf(data=sierraCounties, aes(), fill="white") +
geom_sf(data=sierraAnnual, aes(col=PRECIPITATION)) +
scale_color_gradient(low="orange", high="blue")

## 7.2 Spatial analysis operations

Again, there is a lot more to spatial analysis than we have time to cover. But we’ll explore some particularly useful spatial analysis operations, especially those that contribute to statistical analysis methods we’ll be looking at soon. We’ll start by continuing to look at subsetting or filtering methods, but ones that use spatial relationships to identify what we want to retain or remove from consideration.

### 7.2.1 Using topology to subset

Using spatial relationships can be useful in filtering our data, and there are quite a few topological relationships that can be explored. See for a lot more about topological operations. We’ll look at a relatively simple one that identifies whether a feature is within another one, and apply this method to filter for features within a selection of 5 counties, which we’ll start by identifying by name.

nSierraCo <- CA_counties %>%
filter(NAME %in% c("Plumas","Butte","Sierra","Nevada","Yuba"))

Then we’ll use those counties to select towns (places) that occur within them…

CA_places <- st_read(ex("sierra/CA_places.shp"))
nCAsel <- lengths(st_within(CA_places, nSierraCo)) > 0 # to get TRUE & FALSE
nSierraPlaces <- CA_places[nCAsel,]

… and do the same for the sierraFeb weather stations:

sierra <- st_as_sf(read_csv(ex("sierra/sierraFeb.csv")), coords=c("LONGITUDE","LATITUDE"), crs=4326)
nCAselSta <- lengths(st_within(sierra, nSierraCo)) > 0 # to get TRUE & FALSE
nSierraStations <- sierra[nCAselSta,]
library(maptiles)
nsierraBase <- get_tiles(nSierraStations, provider="OpenTopoMap")
library(tmap)
tmap_mode("plot")
tm_shape(nsierraBase) + tm_rgb(alpha=0.5) +
tm_shape(nSierraCo) + tm_borders() + tm_text("NAME") +
tm_shape(nSierraStations) + tm_symbols(col="blue") +
tm_shape(nSierraPlaces) + tm_symbols(col="red", alpha=0.5) + tm_text("AREANAME")

So far, the above is just subsetting for a map, which may be all we’re wanting to do, but we’ll apply this selection to a distance function in the next section to explore a method using a reduced data set.

### 7.2.2 Centroid

Related to the topological concept of relating features inside other features is creating a new feature in the middle of an existing one, specifically a point placed in the middle of a polygon: a centroid. Centroids are useful when you need point data for some kind of analysis, but that point needs to represent the polygon it’s contained within. The methods we’ll see in the code below include:

• st_centroid() : to derive a single point for each tract that should be approximately in its middle (but must be topologically contained within it, not fooled by an annulus (“doughnut”) shape for example.)
• st_make_valid() : to make an invalid geometry valid (or just check for it). This function that has just become essential now that sf supports spherical instead of just planar data, which is the case BayAreaTracts which ends up containing “slivers” where boundaries slightly under- or over-lap since they were originally built from a planar projection. The st_make_valid() appears to make minor (and typically invisible) corrections to these slivers.
• st_bbox : reads the bounding box, or spatial extent, of any dataset, which we can then use to set the scale to focus on that area. In this case, we’ll focus on the census centroids instead of the statewide CAfreeways for instance.

Let’s see the effect of the centroids and bbox. First just centroids:

library(tidyverse); library(sf); library(igisci)
CA_counties <- st_make_valid(CA_counties) # needed fix for data
ggplot() +
geom_sf(data=CA_counties) +
geom_sf(data=st_centroid(CA_counties))

Here’s an example that also applies the bounding box to establish a mapping scale that covers the Bay Area while some of the data (TRI locations and CAfreeways) are state-wide:

library(tidyverse)
library(sf)
library(igisci)
BayAreaTracts <- st_make_valid(BayAreaTracts)
censusCentroids <- st_centroid(BayAreaTracts)
coords = c("LONGITUDE", "LATITUDE"),
crs=4326) # simple way to specify coordinate reference
bnd <- st_bbox(censusCentroids)
ggplot() +
geom_sf(data = BayAreaCounties, aes(fill = NAME)) +
geom_sf(data = censusCentroids) +
geom_sf(data = CAfreeways, color = "grey", alpha=0.5) +
geom_sf(data = TRI_sp, color = "yellow") +
coord_sf(xlim = c(bnd[1], bnd[3]), ylim = c(bnd[2], bnd[4])) +
labs(title="Bay Area Counties, Freeways and Census Tract Centroids")

### 7.2.3 Distance

Distance is a fundamental spatial measure, used to not only create spatial data (distance between points in surveying or distance to GNSS satellites) but also to analyze it. Note that we can either be referring to planar (from projected coordinate systems) or spherical (from latitude and longitude) great-circle distances. Two common spatial operations involving distance in vector spatial analysis are (a) deriving distances among features, and (b) creating buffer polygons of a specific distance away from features. In raster spatial analysis, we’ll look at deriving distances from target features to each raster cell.

#### 7.2.3.1 Distances among features

The sf st_distance and terra distance functions derive distances between features, either among features of one data set object or between all features in one and all features in another data set.

To see how this works, we’ll look at a purposefully small dataset: a selection of Marble Mountains soil CO2 sampling sites and in-cave water quality sampling sites. We’ll start by reading in the data, and filtering to just get cave water samples and a small set of nearby soil CO2 sampling sites:

library(igisci); library(sf); library(tidyverse)
filter((SAMPLES_ID >= 50) & (SAMPLES_ID < 60)) # these are the cave samples
soilCO2 <- soilCO2all %>% filter(LOC > 20) # soil CO2 samples in the same general area

Here are the six selected soil CO2 samples:

library(tmap); library(maptiles)
marblesTopoBase <- get_tiles(soilCO2, provider="OpenTopoMap")
tmap_mode("plot")
tm_shape(marblesTopoBase) + tm_rgb(alpha = 0.6) +
tm_shape(soilCO2) + tm_symbols(col="CO2_", palette="Reds", size=4) +
tm_shape(soilCO2) + tm_text("LOC")

If you just provide the 6 soil CO2 sample points as a single feature data set input to the st_distance function, it returns a matrix of distances between each, with a diagonal of zeros where the distance would be to itself:

st_distance(filter(soilCO2))
## Units: [m]
##           [,1]      [,2]       [,3]       [,4]     [,5]      [,6]
## [1,]    0.0000  370.5894 1155.64981 1207.62172 3333.529 1439.2366
## [2,]  370.5894    0.0000  973.73559 1039.45041 3067.106 1248.9347
## [3,] 1155.6498  973.7356    0.00000   75.14093 2207.019  283.6722
## [4,] 1207.6217 1039.4504   75.14093    0.00000 2174.493  237.7024
## [5,] 3333.5290 3067.1061 2207.01903 2174.49276    0.000 1938.2985
## [6,] 1439.2366 1248.9347  283.67215  237.70236 1938.299    0.0000

Then we’ll look at distances between this same set of soil CO2 samples with water samples collected in caves, where the effect of elevated soil CO2 values might influence solution processes reflected in cave waters.

library(tmap)
tmap_mode("plot")
marblesTopoBase <- get_tiles(soilCO2, provider="OpenTopoMap")

tm_shape(marblesTopoBase) + tm_rgb() +
tm_shape(cave_wsamples) + tm_symbols(col="CATOT", palette="Blues") +
tm_shape(cave_wsamples) + tm_text("SAMPLES_ID") +
tm_shape(soilCO2) + tm_symbols(col="CO2_", palette="Reds") +
tm_shape(soilCO2) + tm_text("LOC")
soilwater <- st_distance(soilCO2, cave_wsamples)
soilwater
## Units: [m]
##          [,1]     [,2]     [,3]      [,4]      [,5]      [,6]      [,7]
## [1,] 2384.210 2271.521 2169.301 1985.6093 1980.0314 2004.1697 1905.9543
## [2,] 2029.748 1920.783 1826.579 1815.2653 1820.0496 1835.9465 1798.1216
## [3,] 1611.381 1480.688 1334.287  842.8228  846.3210  863.1026  849.7313
## [4,] 1637.998 1506.938 1357.582  781.9741  782.4215  801.6262  776.0732
## [5,] 1590.469 1578.730 1532.465 1526.3315 1567.5677 1520.1399 1820.3651
## [6,] 1506.358 1375.757 1220.000  567.8210  578.1919  589.1443  638.8615

In this case, the 6 soil CO2 samples are the rows, and the 7 cave water sample locations are the columns. We aren’t really relating the values but just looking at distances. An analysis of this data might not be very informative because the caves aren’t very near the soil samples, and conduit cave hydrology doesn’t lend itself to looking at euclidean distance, but the purpose of this example is just to comprehend the results of the sf::st_distance or similarly the terra::distance function.

#### 7.2.3.2 Distance to the nearest feature, abstracted from distance matrix

However, let’s process the matrix a bit to find the distance from each soil CO2 sample to the closest cave water sample:

soilCO2d <- soilCO2 %>% mutate(dist2cave = min(soilwater[1,]))
for (i in 1:length(soilwater[,1])) soilCO2d[i,"dist2cave"] <- min(soilwater[i,])
soilCO2d %>% select(DESCRIPTIO, dist2cave) %>% st_set_geometry(NULL)
##                                              DESCRIPTIO     dist2cave
## 1                Super Sink moraine, low point W of 241 1905.9543 [m]
## 2      Small sink, first in string on hike to SuperSink 1798.1216 [m]
## 3        meadow on bench above Mbl Valley, 25' E of PCT  842.8228 [m]
## 4        red fir forest S of upper meadow, 30' W of PCT  776.0732 [m]
## 5            saddle betw Lower Skyhigh (E) & Frying Pan 1520.1399 [m]
## 6 E end of wide soil-filled 10m fissure N of lower camp  567.8210 [m]

… or since we can also look at distances to lines or polygons, we can find the distance from CO2 sampling locations to the closest stream:

library(igisci); library(sf); library(tidyverse)
streams <- st_read(ex("marbles/streams.shp"))
strCO2 <- st_distance(soilCO2all, streams)
strCO2d <- soilCO2all %>% mutate(dist2stream = min(strCO2[1,]))
for (i in 1:length(strCO2[,1])) strCO2d[i,"dist2stream"] <- min(strCO2[i,])
marblesTopoBase <- get_tiles(soilCO2, provider="OpenTopoMap")
tm_shape(marblesTopoBase) + tm_rgb() +
tm_shape(streams) + tm_lines(col="blue") +
tm_shape(strCO2d) + tm_symbols(col="dist2stream")

#### 7.2.3.3 Nearest feature detection

As we just saw, the matrix derived from st_distance when applied to feature data sets could be used for further analyses, such as this distance to the nearest place. But there’s another approach to this using a specific function that identifies the nearest feature: st_nearest_feature, so we’ll look at this with the previously filtered northern Sierra places and weather stations. We start by using st_nearest_feature to create an index vector of the nearest place to each station, and grab its location geometry:

nearest_Place <- st_nearest_feature(nSierraStations, nSierraPlaces)
near_Place_loc <- nSierraPlaces$geometry[nearest_Place] Then add the distance to that nearest place to our nSierraStations sf. Note that we’re using st_distance with 2 vector inputs as before, but ending up with just one distance per feature (instead of a matrix) with the setting by_element=TRUE nSierraStations <- nSierraStations %>% mutate(d2Place = st_distance(nSierraStations, near_Place_loc, by_element=TRUE), d2Place = units::drop_units(d2Place)) … and of course map the results: sierraStreetBase <- get_tiles(nSierraStations, provider="OpenStreetMap") tm_shape(sierraStreetBase) + tm_rgb() + tm_shape(nSierraCo) + tm_borders() + tm_text("NAME") + tm_shape(nSierraStations) + tm_symbols(col="d2Place") + tm_shape(nSierraPlaces) + tm_symbols(col="blue", alpha=0.5) That’s probably enough examples of using distance to nearest feature so we can see how it works, but to see an example with a larger data set, an example in Appendix A7.2 looks at the proximity of TRI sites to health data at census tracts. ### 7.2.4 Buffers Creating buffers, or polygons defining the area within some distance of a feature, is commonly used in GIS. Since you need to specify that distance (or read it from a variable for each feature), you need to know what the horizontal distance units are for your data. If GCS, these will be decimal degrees and 1 degree is a long way, about 111 km (or 69 miles), though that differs for longitude where 1 degree of longitude is 111 km * cos(latitude). If in UTM, the horizontal distance will be in metres, but in the US, state plane coordinates are typically in feet. So let’s read the trails shapefile from the Marble Mountains and look for its units: library(igisci) library(sf); library(tidyverse) trails <- st_read(ex("marbles/trails.shp")) Then we know we’re in metres, so we’ll create a 100-m buffer this way. trail_buff0 <- st_buffer(trails,100) ggplot(trail_buff0) + geom_sf() #### 7.2.4.1 The units package Since the spatial data are in UTM, we can just specify the distance in metres. However if the data were in decimal degrees of latitude & longitude (GCS), we would need to let the function know that we’re providing it metres so it can transform that to work with the GCS, using units::set_units(100, "m") instead of just 100, for the above example where we are creating a 100 m buffer. ### 7.2.5 Spatial Overlay: Union and Intersection Overlay operations are described in the sf cheat sheet under “Geometry operations.” These are useful to explore, but a couple we’ll look at are union and intersection. Normally these methods have multiple inputs, but we’ll start with one that can also be used to dissolve boundaries, st_union – if only one input is provided it appears to do a dissolve: trail_buff <- st_union(trail_buff0) ggplot(trail_buff) + geom_sf() For a clearer example with the normal multiple input, we’ll intersect a 100m buffer around streams and a 100m buffer around trails … streams <- st_read(ex("marbles/streams.shp")) trail_buff <- st_buffer(trails, 100) str_buff <- st_buffer(streams,100) strtrInt <- st_intersection(trail_buff,str_buff) …to show areas that are close to streams and trails: ggplot(strtrInt) + geom_sf(fill="green") + geom_sf(data=trails, col="red") + geom_sf(data=streams, col="blue") Or how about a union of these two buffers? We’ll also dissolve the boundaries using union with a single input (the first union) to dissolve those internal overlays: strtrUnion <- st_union(st_union(trail_buff,str_buff)) ggplot(strtrUnion) + geom_sf(fill="green") + geom_sf(data=trails, col="red") + geom_sf(data=streams, col="blue") ### 7.2.6 Clip with st_crop Clipping a GIS layer to a rectangle (or to a polygon) is often useful. We’ll clip to a rectangle based on latitude and longitude limits we’ll specify, however since our data is in UTM, we’ll need to use st_transform to get it to the right coordinates: xmin=-123.21; xmax=-123.18; ymin=41.55; ymax=41.57 clipMatrix <- rbind(c(xmin,ymin),c(xmin,ymax),c(xmax,ymax),c(xmax,ymin),c(xmin,ymin)) clipGCS <- st_sfc(st_polygon(list(clipMatrix)),crs=4326) bufferCrop <- st_crop(strtrUnion,st_transform(clipGCS,crs=st_crs(strtrUnion))) bnd <- st_bbox(bufferCrop) ggplot(bufferCrop) + geom_sf(fill="green") + geom_sf(data=trails, col="red") + geom_sf(data=streams, col="blue") + coord_sf(xlim = c(bnd[1], bnd[3]), ylim = c(bnd[2], bnd[4])) #### 7.2.6.1 sf or terra for vector spatial operations? Note: there are other geometric operations in sf beyond what we’ve looked at. See the cheat sheet and other resources at https://r-spatial.github.io/sf . The terra system also has many vector tools (such as terra::union and terra::buffer), that work with and create SpatVector spatial data objects. As noted earlier, these S4 spatial data can be created from (S3) sf data with terra::vect and vice versa with sf::st_as_sf. We’ll mostly focus on sf for vector and terra for raster, but to learn more about SpatVector data and operations in terra, see https://rspatial.org . For instance, there’s a similar terra operation for one of the things we just did, but instead of using union to dissolve the internal boundaries like st_union did, uses aggregate to remove boundaries between polygons with the same codes: trails <- vect(ex("marbles/trails.shp")) trailbuff <- aggregate(buffer(trails,100)) plot(trailbuff) ### 7.2.7 Spatial join with st_join A spatial join can do many things, but we’ll just look at its simplest application – connecting a point with the polygon that it’s in. In this case, we want to join the attribute data in BayAreaTracts with EPA Toxic Release Inventory (TRI) point data (at factories and other point sources) and then display a few ethnicity variables from the census, associated spatially with the TRI point locations. We’ll be making better maps later; this is a quick plot() display to show that the spatial join worked. library(igisci); library(tidyverse); library(sf) TRI_sp <- st_as_sf(read_csv(ex("TRI/TRI_2017_CA.csv")), coords = c("LONGITUDE", "LATITUDE"), crs=4326) %>% st_join(st_make_valid(BayAreaTracts)) %>% filter(!is.na(TRACT)) %>% # removes points not in the Bay Area -- not in BayAreaTracts dplyr::select(POP2012:HISPANIC) plot(TRI_sp) ## 7.3 Exploring methods We’ve looked at a selection of feature-based spatial analysis functions mostly in the sf package. There are a lot more discussed in the “Spatial data operations” and “Geometry operations” chapters of Geocomputation (https://geocompr.robinlovelace.net/, ) that are worth exploring (and still others in the terra package describe at https://rspatial.org, ), especially when you run into a task that the tools we’ve learned won’t do. There is also good coverage of transformation and reprojection methods in the “Reprojecting geographic data” and data access methods in the “Geographic data I/O” chapter of Geocomputation. And the Simple Features for R reference () site includes a complete reference for all of its functions, as does https://rspatial.org for terra. ## 7.4 Exercises 1. (Assuming you wrote them in the last chapter,) read in your western states “data/W_States.shp” and peaks “data/peaks.shp” data, then use a spatial join to add the peak points to the states to provide a new attribute maximum elevation, and display that using geom_sf_text() with the state polygons. Note that joining from the states to the peaks works because there’s a one-to-one correspondence between states and maximum peaks. (If you didn’t write them, you’ll need to repeat your code that built them from the previous chapter.) 1. Also using the western states data, change the map to the view mode, but don’t use the state borders since the basemap will have them. Just before adding shapes, set the basemap to leaflet::providers$Esri.NatGeoWorldMap, then continue to the peaks after the + to see the peaks on a National Geographic basemap.
1. Using two shape files of your own choice, not from igisci, read them in as sf data, and perform a spatial join to join the polygons to the point data. Then display the point feature data frame, and create a ggplot scatter plot or boxplot graph where the two variables are related, preferably with a separate categorical variable to provide color.

2. From the above spatially joined data create a map where the points are colored by data brought in from the spatial join; can be either a categorical or continuous variable.

3. Create an sf that represents all areas within 50 km of a TRI facility in California that has >10000 pounds of total stack air release for all gases, clipped (intersected) with the state of California as provided in the CA counties data set. Then use this to create a map of California showing the clipped buffered areas in red, with California counties and those selected large-release TRI facilities in black dots, as shown here. To create a variable representing 50 km to provide to the dist parameter in st_buffer [this is needed since the spatial data are in GCS], use the units::set_units function, something like this: D50km <- units::set_units(50, "km")`

### References

Berry, Brian Joe Lobley, and Duane Francis Marble. 1968. Spatial Analysis: A Reader in Statistical Geography. Prentice-Hall.
Hijmans, Robert J. n.d. Spatial Data Science. https://rspatial.org.
Lovelace, Robin, Jakuv Nowosad, and Jannes Muenchow. 2019. Geocomputation with r. CRC Press. https://geocompr.robinlovelace.net/.
Simple Features for r. n.d. https://r-spatial.github.io/sf/.

format: plain


text:
# All Questions

32 views

### Singularities of the Quantum propagator (baby version)

Given $a,b \in \mathfrak{su}(4)$ which are taken to generate the whole algebra, consider the following map $V:\mathbb{R}^{2} \rightarrow SU(4)$: $V : (w_1, w_{2}) \mapsto e^{(a+w_2 b)} e^{(a+w_1 b)}$ ...
284 views


text:
# COVID-19 outbreak: the case of Portugal(Update)

### COVID-19: a data epidemic

With the outbreak of COVID-19 one thing that is certain is that never before a virus has gone so much viral on the internet. Especially, a lot of data about the spread of the virus is going around.

In the space of a few weeks, complex terms like “group immunity” (herd immunity) or “flattening the curve” started to circulate on social networks.

Here we will try an approach that demonstrates the limitations of the model from the previous post The importance of “flattening the curve”.
This post is based on Contagiousness of COVID-19 Part I: Improvements of Mathematical Fitting (Guest Post), this post compared to the previous one shows that the fitting of the data with the SIR model is tricky, the general problem is that the fitting-algorithm is not always finding it’s way to the best solution.

### Why doesn’t the algorithm converge to the optimal solution?

There are two main reasons why the model is not converging well.

### Early stopping of the algorithm

The first reason is that the optim algorithm is stopping too early before it has found the right solution.

### Ill-conditioned problem

The second reason for the bad convergence behaviour of the algorithm is that the problem is ill-conditioned.

### The latest data from:

https://github.com/CSSEGISandData/COVID-19/tree/master/csse_covid_19_data/csse_covid_19_time_series

### Currently the calculation of R0 by the model of the previous post

gives: R0 = 1.2777406

### R0 by the current model

The current model gives: R0 = 1.0620105 as we see the result is quite different.

### Some differences of the SIR model

This SIR model uses the parameters $K = \beta - \gamma$ and $R_0 = \frac{\beta}{\gamma}$

### Final conclusions

Based on this model the peak of the epidemic has already happened on day 2020-04-12 with a maximum of 17 870.
This is all we want, but it doesn’t mean it is correct. Just because we use a mathematical model does not mean that our conclusions/predictions are trustworthy. We need to challenge the premises which are the underlying data and models.

### References

If you liked this post, you can share it with your followers or follow me on Twitter!


text:
# Supersymmetry notation question

1. Oct 26, 2008

### StatusX

In super yang mills theories in 4,6,10 dimensions, the supersymmetry transformation is often written as (ignoring color indices):

$$\delta A_\mu = i \bar \alpha \gamma_\mu \lambda - i \bar \lambda \gamma_\mu \alpha$$

$$\delta \lambda = c F^{\mu \nu} [ \gamma_\mu, \gamma_\nu] \alpha$$

where c is some constant depending on dimension, and $\alpha$ is the parameter of the transformation, a fermionic c-number spinor.

I have a few questions about this. First of all, are we supposed to assume $\alpha$ has the same properties as $\lambda$, ie, wrt majorana and weyl -ness? It seems like we should to get the right number of supercharges, and maybe to preserve the corresponding property of $\lambda$ after a transformation, but this is never mentioned.

Second, what exactly do these transformations mean in terms of the susy generators Q? Do these generators fit into a spinor with the same properties as $\alpha$ and $\lambda$? If so, and if we call this spinor Q, can we write:

$$\delta \mathcal{O} = [ \bar \alpha Q, \mathcal{O} ]$$

This doesn't seem right, because if $\alpha$ is Weyl, the RHS doesn't depend on the conjugates of Q. Maybe it's something like:

$$\delta \mathcal{O} = [ \bar \alpha Q + \bar Q \alpha, \mathcal{O} ]$$

Is this right? And in any case, what would be the easiest way to determine the anticommutators of the Q's given the transformations in the form of the first equations above?

2. Oct 26, 2008

### nrqed

What I have seen is this, instead:
$$\delta \mathcal{O} = [ \alpha Q + \bar Q \bar \alpha, \mathcal{O} ]$$

There are two ways to determine the anticommutation rules: finding the supercurrent generating the transformation, getting the explicit charges (as the integral of the zeroth component of j^mu ) and then calculating the explicit anticommutators.

The other way is to calculate the commutator of two variations (each with a different parameter) on the fields $$(\delta_\alpha \delta_\beta - \delta_\beta \delta_\alpha) A_\mu$$ and then you do the same thing using the supercharges, and then set the two results equal to one another.

3. Oct 30, 2008

### BenTheMan

The $$\alpha$$ is there to get the indices right. As to your question about "majorana-ness" or "weyl-ness", the infinitessimal $$\alpha$$ transforms as a spinor of the Lorentz group as your $$\lambda$$, so in that sense, yes. Again, you can see this by just putting in the spinor indices.


text:
# Surveying Questions and Answers – Reduction in Levelling

«
»

This set of Surveying Multiple Choice Questions & Answers (MCQs) focuses on “Reduction in Levelling”.

1. Height of the Instrument method is a less tedious and simple process.
a) False
b) True

Explanation: The above statement is true because it involves simple calculations when compared to Rise and fall method, which can be completed with minimal effort.

2. While doing construction work, which among the following is more suitable?
a) Rise and Fall method
b) Traversing
c) Height of the Instrument method(H.I)
d) Compass Surveying

Explanation: Height of the Instrument method is less tedious than Rise and fall method. Moreover, this process is suitable for taking numerous readings from same instrument setting. Traversing is a process of establishing control points and Compass surveying involves in finding the bearings.

3. The formula for calculating R.L can be given as _________
a) H.I+F.S
b) H.I-F.S
c) H.I-B.S
d) H.I+B.S

Explanation: By subtracting the fore sight value from height of the instrument, the value of reduced level for the next set of reading can be obtained.

4. Which of the following indicates the formula for arithmetic check?
a) ΣB.S-ΣF.S=Last R.L-First R.L
b) ΣF.S-ΣB.S=Last R.L-First R.L
c) ΣB.S+ΣF.S=First R.L-Last R.L
d) ΣF.S+ΣB.S=Last R.L-First R.L

Explanation: If the difference in summation of back sight and fore sight is equal to the difference of last R.L and first R.L, then obtained set of values for finding difference in elevation are correct.

5. Rise and fall method provides check in calculations for all sights.
a) True
b) False

Explanation: Since the check for intermediate sights is not available in H.I method, it may lead to errors while doing calculations.

6. Which of the following represents a form of Bench Mark (B.M)?
a) True Benchmark
b) Assumed Benchmark
c) Datum
d) Arbitrary Benchmark

Explanation: Benchmark is a point of known elevation taken as reference. It is classified as Arbitrary, G.T.S, Permanent and Temporary.

7. If the staff at the station point is not held vertically, the R.L at the observation would be ______________
a) Less than true R.L
b) Greater than true R.L
c) Equal to the true R.L
d) Two times the true R.L

Explanation: Due to irregular holding of the staff, the values which are obtained by the levelling instrument might lead to decrease in R.L.

8. If the R.L of a B.M is 100m and back sight is 1.225m, find the H.I at the station?
a) 101.225m
b) -101.225m
c) 98.775m
d) -98.775m

Explanation: We know that, H.I=R.L+B.S
Then, H.I= 100+1.225 H.I=101.225 m.

9. The combined correction for curvature and refraction can be given as _______
a) C = 14d2/6R
b) C = 6d2/7R
c) C = 7d2/2R
d) C = 6d2/14R

Explanation: By subtracting the correction due to curvature from correction due to refraction we can get the combined correction i.e., $$C = \frac{d^2}{2R} – (\frac{1}{7}*\frac{d^2}{2R}).$$

10. Find the correction for curvature and correction for refraction, if the value of d = 2400 m?
a) 0.425, 0.604
b) 0.452, 0.064
c) 0.064, 0.452
d) 0.604, 0.425

Explanation: Correction for curvature = $$\frac{d^2}{2R} = \frac{2.4^2}{2*6370}*1000 = 0.452m$$ Correction for refraction $$= \frac{1}{7} * C_c = \frac{0.452}{7} = 0.064m.$$

11. Find the value of R.L, if B.M = 400 m, B.S = 1.142 m, F.S = 2.121 by using rise and fall method?
a) 400.79 m
b) 400.97 m
c) 409.79 m
d) 399.02 m

Explanation: In the rise and fall method, first we must calculate the difference between B.S and F.S. We get 1.142 – 2.121 = -0.979 m, which is negative. It means we have to subtract it from the given B.M for obtaining R.L i.e., R.L = 400 – 0.979 = 399.021 m.

12. If d = 2.94 km, what would be the combined correction for curvature and refraction?
a) 1.85 km
b) 0.85 km
c) 0.58 km
d) 1.58 km

Explanation: We know that combined correction for curvature can be given as $$C = \frac{6d^2}{14R}$$ On substituting the value the of d in the above equation we get,
$$C = \frac{6d^2}{14R} = \frac{6*2.94^2}{14*6370} = 0.5814 km.$$


text:
# Bad line overlap in PSTricks figure

Consider the following code (which is almost the same as this):

\documentclass{article}

\usepackage{animate}
\usepackage[locale=DE]{siunitx}

\def\vinkelA{12 }
\pstFPdiv\faktor{1}{3}
\makeatletter
\pst@getsinandcos{\vinkelA}
\pstFPmul\MaxLW{2}{\MaxLW}
\def\PolyLine{%
\psline(B)(A)(D)
}

\def\light#1{% Sun beams.
\psset{
unit=0.7
}
\begin{pspicture}(-\faktorC,-\faktorC)(\faktorC,\faktorD)
\pst@getsinandcos{#1}
\ifnum #1 = 90 \let\RelLW\MaxLW
\else
\ifnum #1 > 90 \pstFPmul\RelLW{\MaxLW}{\pst@cos}
\else          \pstFPmul\RelLW{\MaxLW}{\pst@sin}
\fi
\fi
\pnode(0,0){C}
% Filling
\pscustom[
linewidth=2pt,
linecolor=red,
]{\PolyLine}
\begin{psclip}{% Clipping.
\pscustom[
linestyle=none,
dimen=inner
]{%
\PolyLine
}
}
\pcline[
linecolor=yellow,
linewidth=\RelLW,
](0,0)(!#1 dup 90 ne {-1 exch neg Tan neg} {0 -1} ifelse)}
\end{psclip}
\pscustom[
linewidth=2pt,
linecolor=red
]{\PolyLine}% Better clipping.
\psline[
linestyle=dotted
\pswedge(0,0){1}{!180 #1 sub}{180}
\uput{1}[!180 #1 2 div sub](0,0){\footnotesize \SI{#1}{\degree}}
\psline[
linestyle=dotted
](0,0)(!3 180 #1 sub PtoC)
}
\end{pspicture}
}

\begin{document}

\begin{animateinline}[poster=first,controls,palindrome]{2}
\multiframe{121}{iA=30+1}{\light{\iA}}
\end{animateinline}

\end{document}

I don't like the way red curve 'hits' the yellow area; how do I improve this? (I'm not exactly sure what I want but I'll tell if the answer(s) given is/are what I'm looking for.)

P.S. Feel free to add more tags.

-
you could draw the red lines first, and then the yellow thing on top? too simplistic? :) –  cmhughes Sep 21 '13 at 15:30
@cmhughes It could be good! :) My problem is that I put the code for the red curve in the wrong place; the upper part of the yellow parallellogram disappears when I rearrange the code. Can I get you to rearrange the code correctly for me in an answer? –  Svend Tveskæg Sep 21 '13 at 15:41

\documentclass{article}

\usepackage{animate}
\usepackage[locale=DE]{siunitx}

\def\vinkelA{12 }
\pstFPdiv\faktor{1}{3}
\makeatletter
\pst@getsinandcos{\vinkelA}
\pstFPmul\MaxLW{2}{\MaxLW}
\newcommand\PolyLine[1][\vinkelA]{%
\psline(B)(A)(D)

\def\light#1{% Sun beams.
\psset{unit=0.7}
\begin{pspicture}(-\faktorC,-\faktorC)(\faktorC,\faktorD)
\pst@getsinandcos{#1}
\ifnum #1 = 90 \let\RelLW\MaxLW
\else
\ifnum #1 > 90 \pstFPmul\RelLW{\MaxLW}{\pst@cos}
\else          \pstFPmul\RelLW{\MaxLW}{\pst@sin}
\fi
\fi
% Filling
\pscustom[
linestyle=none,
\pscustom[linewidth=2pt,linecolor=red]{\PolyLine[0]}
\begin{psclip}{% Clipping.
\pscustom[linestyle=none,dimen=inner]{%
\PolyLine}
}
}
](0,0)(!#1 dup 90 ne {-1 exch neg Tan neg} {0 -1} ifelse)}
\end{psclip}
\pswedge(0,0){1}{!180 #1 sub}{180}
\uput{1}[!180 #1 2 div sub](0,0){\footnotesize \SI{#1}{\degree}}
\psline[linestyle=dotted](0,0)(!3 180 #1 sub PtoC)
}
\end{pspicture}
}

\begin{document}

\begin{animateinline}[poster=first,controls,palindrome]{2}
\multiframe{121}{iA=30+1}{\light{\iA}}
\end{animateinline}

\end{document}

-
It looks good. Come to think of it, I would like the red curve to be cut off vertical at both sides of the yellow parallellogram since the drawing illustrates light coming through a hole in a ceiling. Furthermore, the light should go through the hole hitting the top of the left-hand side of the curve and the bottom of the right-hand side of the curve. (I hope it makes sence.) –  Svend Tveskæg Sep 21 '13 at 16:11
I changed the code. Substract the linewidth from the clip area for the yellow line. A vertical cut of the line is possible if you shorten the line at the end yellow edges. –  Herbert Sep 21 '13 at 16:24
I see that you have incorporated the subtraction of the linewidth (nice!) but it is not compeltely perfect; the right-most part of the parallellogram overlaps a tiny bit of the red curve. Also, I can't figure out how to get a vertical cut of the line. –  Svend Tveskæg Sep 24 '13 at 5:24


text:
# D. K. Musaev

Search this author in Google Scholar

Articles: 3

### On generalization of the Freudenthal's theorem for compact irreducible standard polyhedric representation for superparacompact complete metrizable spaces

D. K. Musaev

Methods Funct. Anal. Topology 17 (2011), no. 1, 58-64

In this paper for superparacompact complete metrizable spaces, the Freudenthal's theorem for compact irreducible standard polyhedral representation is ge e alized. Furthermore, for superparacompact metric spaces the following is strengthened: 1) the Morita's theorem about universality of the product $Q^\infty\times B(\tau)$ of Hilbert cube $Q^\infty$ to generalized Baire space $B(\tau)$ of the weight $\tau$ in the space of all strongly metrizable spaces of weight $\le \tau$; 2) Nagata's theorem about universality of the product $\Phi^n\times B(\tau)$ of the universal $n$-dimensional compact $\Phi^n$ to $B(\tau)$ in the space of all strongly metrizable spaces $\le\tau$ and dimension $\operatorname{dim}X\le n.$

### On bicompactness of quasi-component of continuous mappings and characterization of tubular (weakly) $\Pi$-complete and (weakly) $\Pi$-complete mappings with the use of injections

D. K. Musaev

Methods Funct. Anal. Topology 10 (2004), no. 4, 58-73

### Tubular (weakly) Π-complete and (weakly) Π-completeness of continuous mappings, their properties and characterizations by the use of morphisms

D. K. Musaev

Methods Funct. Anal. Topology 9 (2003), no. 3, 241-246