source_id
int64 1
4.64M
| question
stringlengths 0
28.4k
| response
stringlengths 0
28.8k
| metadata
dict |
---|---|---|---|
30,647 |
I would like to take the following data: insertValues = {r, x};
insertPositions = {{1}, {5}};
originalList = {a, b, c, d, e, f, g}; and generate output that looks like this: {r,a,b,c,d,x,e,f,g} Mathematica 's Insert command seems limited in that it does not allow you to insert multiple elements simultaneously into different positions in a list. I wrote an ugly While[] loop to accomplish this, and it works, but seems inappropriate for Mathematica's functional approach to coding. Is there a "simpler" way to accomplish this goal with a functional approach? Thank you. insertValues = {r, x};
insertPositions = {{1}, {5}};
originalList = {a, b, c, d, e, f, g};
loopCounter = 0;
posCounter = 0;
final = originalList;
While[loopCounter < Length[insertValues],
final =
Insert[final, insertValues[[loopCounter + 1]],
(insertpositions[[loopCounter + 1]] + posCounter)];
loopCounter++;
posCounter++
];
|
New developments rasher posted a new answer with clean and well performing code that caused me to look again at this problem. (It well deserves your vote.) I see now that there are good ways to approach this problem that haven't yet been fully developed. Fundamentally rasher's code operates by Sort , but I don't think even he realized this as Riffle et al are superfluous. We merely need Ordering and Part applied to joined lists of the correct order: oInsert[list_, val_, pos_] :=
Join[val, list][[ Ordering @ Join[pos, Range @ Length @ list] ]] In a way rasher solved the problem twice : Riffle and sa[[ps]] = reps already place the elements in the proper order; one merely needs to get rid of the zeros. We could use DeleteCases but pattern based methods are slow. Instead I reimplemented the Riffle operation in terms of SparseArray , but to make it efficient I had to be clever and unfortunately here that (so far) implies less clean code. saInsert[list_, val_, pos_] :=
With[{no = Length[list], ni = Length[val]},
SparseArray[
Automatic, {2, no + 1}, 0,
{1, {{0, ni, no + ni}, pos ~Join~ Range[no] ~Partition~ 1}, val ~Join~ list}
]\[Transpose]["NonzeroValues"]
] This ugly bit of code manually constructs a two row SparseArray , the upper row being the insertion elements and the lower being the original list. It then transposes them, and extracts the "NonzeroValues" . (Despite the name these are actually the non-background values; this code still works correctly with zeros.) Rudimentary test of both new methods: oInsert[{a, b, c, d, e}, {W, X, Y, Z}, {1, 2, 4, 6}]
saInsert[{a, b, c, d, e}, {W, X, Y, Z}, {1, 2, 4, 6}] {W, a, X, b, c, Y, d, e, Z}
{W, a, X, b, c, Y, d, e, Z} I shall add timings for these functions later, but to summarize my early findings: multiInsert2 is still the fastest for a limited number of insertions into a long list saInsert is superior to all other methods posted so far for a greater number of insertions into a packed list oInsert is competitive with saInsert and rashernator on unpacked lists. It is faster than rashernator on packed lists. Original Method If your list is a vector (has no sub-lists) this is perhaps the simplest way, and likely competitively fast: m = origlist;
m[[{1, 5}]] = {{r, x}, m[[{1, 5}]]}\[Transpose]
Flatten[m] {r, a, b, c, d, x, e, f, g} Edit: Ray Koopman points out that this method, by itself, does not handle an edge case in Insert where the position is one greater than the length of the list, i.e. Insert[{1,2,3}, x, 4] . This is accounted for in the function below by padding the list as required. If your list is not a vector (as defined above) we could use a different head for the inserted elements and then replace it with Sequence to effect a flatten. Here is a function that handles both cases, selecting between the methods for best performance: multiInsert[list_List, val_, pos_] /; Length@val == Length@pos :=
Module[{m = list, f, pad},
pad[x_] /; Max@pos == Length@list + 1 := AppendTo[m, x];
If[VectorQ[val] && VectorQ[list],
pad[{ }]; m[[pos]] = Transpose @ {val, m[[pos]]}; Flatten[m],
pad[f[]]; m[[pos]] = MapThread[f, {val, m[[pos]]}]; m /. f -> Sequence
]
] Input is a little different from yours: multiInsert[Range@15, {a, b, c}, {3, 7, 13}] {1, 2, a, 3, 4, 5, 6, b, 7, 8, 9, 10, 11, 12, c, 13, 14, 15} Preallocate Method Nasser proposed a method of preallocating the array. This idea was promising if it could be optimized because a packed array could be preserved throughout the process theoretically reducing memory and computation time. His implementation was limited in performance because it used a tag that necessitated unpacking and because searching for that tag using Position is slow. Here is an implementation that directly calculates the runs of original values rather than tagging and finding them afterward. multiInsert2[list_, val_, pos_] /; Length@val == Length@pos :=
Module[{new, start, end, offset, n1, n2},
{n1, n2} = Length /@ {list, val};
new = ConstantArray[0, n1 + n2];
start = Prepend[pos, 1];
end = Append[pos - 1, n1];
offset = Range[0, n2];
MapThread[
new[[# ;; #2]] = list[[#3 ;; #4]]; &,
{offset + start, offset + end, start, end}
];
new[[pos + Range[0, n2 - 1]]] = val;
new
] This function appear to be best for a moderate number of insertions into a long list. (See below) Notes and timings Ray Koopman posted a very elegant method, which on reflection I've seen before though I cannot remember where. I voted for that method but there is reason to use the longer forms that belisarius and I proposed: speed on long lists. Every Insert operation reallocates the array which takes time proportional to the length of the list. As such, a method using Fold will slow down considerably when doing many insertions into a very long list. I will call Ray Koopman's code foldInsert : foldInsert[list_, val_, pos_] /; Length@val == Length@pos :=
Fold[
Insert[#1, #2[[2]], #2[[1]]] &,
list,
Reverse @ Sort @ Transpose @ {pos, val}
] And using this timing code for the three functions multiInsert , multiInsert2 , foldInsert : timeAvg =
Function[func,
Do[If[# > 0.3, Return[#/5^i]] & @@ Timing@Do[func, {5^i}], {i, 0, 15}],
HoldFirst];
time[n_Integer, k_Integer, rand_: RandomInteger] :=
Module[{start, vals, pos},
start = Range@n;
vals = rand[9, k];
pos = Sort @ RandomSample[start, k];
timeAvg @ #[start, vals, pos] & /@ {multiInsert, multiInsert2, foldInsert}
] With 3500 insertions into a length 5000 list: time[5000, 3500] {0.0017968, 0.007368, 0.01372} With five insertions into a length 500,000 list: time[500000, 5] {0.02432, 0.0006736, 0.001448} With 7500 insertions into the length 500,000 list: time[500000, 7500] {0.03244, 0.01812, 5.038} All timings above were performing with integer into integer insertions. If inserting reals unpacking is necessary. Here are a few timings for that situation: time[150000, 50, RandomReal]
time[150000, 500, RandomReal]
time[150000, 5000, RandomReal] {0.01372, 0.005488, 0.0624} {0.01308, 0.007368, 0.592} {0.01684, 0.01748, 8.658}
|
{
"source": [
"https://mathematica.stackexchange.com/questions/30647",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/249/"
]
}
|
30,748 |
Context I'm trying to setup a connection between Mathematica and Google Docs. Specifically, I would like to be able to export data to a Google Spreadsheet (Note: if the spreadsheet is public it's very easy to import data to Mathematica , so the problem here is only how to export data to a Google Spreadsheet). I have little knowledge of Java, but as far as I could read in many posts and documentations (for instance, here , here , here , here , here , here ), there are several Java commands and classes involved in the process. I believe there are basically two steps involved in this problem: 1) Get the OAuth authentication from Google (you can get familiar with OAuth here ); 2) Export to Google Spreadsheet using GoogleData libraries (found here ). I know there is a commercial package doing exactly that ( link ), but I would like to be able to control everything from Mathematica . Attempt As said, I have little knowledge of Java. So this is not a serious attempt to solve this problem, but only a concatenation of ideas (hoping someone could actually help me in the process). I believe the first step to achieve the Mathematica -Google Docs connection is to modify the Google Account security definitions ( admin.google.com/AdminHome ) to allow API access and also generate an OAuth-key. So far, so good. From now on, I'm completely lost. I believe the next step would be: 1) Create the OAuth token using the OAuth-key from Google. Something like this: token = HTTPClient`OAuthAuthentication[
"ConsumerKey" -> "mywebaddress.com",
"ConsumerSecret" -> "OAuth-key from Google",
"RequestEndpoint" -> "https://accounts.google.com/OAuthGetRequestToken",
"AuthorizeEndpoint" -> "https://accounts.google.com/o/oauth2/auth",
"AccessEndpoint" -> "https://accounts.google.com/o/oauth2/token"]; Do I need anything else inside the token?) 2) URLFetch the data with the correct methods A list of methods to manipulate a Google spreadsheet can be found here . However, I'm not able to put them in the correct syntax inside Mathematica . Something like this: url="https://spreadsheets.google.com/feeds/cells/{spreadsheet_key}/{active_sheet}/
private/full/{active_cell}/sheet.setColumnWidth(1, 200)"
URLFetch[url,"OAuthAuthentication" -> token] So, when I try to use the code above I get the following error messages: HTTPClient OAuthSignURL::nopt: The option OAuthAuthentication is missing in HTTPClient OAuth Private OAuthURLFetchList[ https://spreadsheets.google.com/feeds/cells/ {sheet_key}/{sheet_sheet}/private/full/{sheet_cell}/sheet.setColumnWidth(1, 200),{CredentialsProvider->None,<<1>>,<<1>>,OAuthAuthentication-><<30>>[<<30>>[<<30>>[<<30>>[<<1>>]]]]}].
General::stop: Further output of HTTPClient`OAuthSignURL::nopt will be suppressed during this calculation. I'm clearly doing lots of wrong things, however I believe someone in MMA.SE could help me to achieve this connection between Mathematica and Google Docs.
|
Update If I were to do this today, I would probably use Google's SDK for Java and JavaLink, which would allow for a better solution. Some have asked me why I said that we have to involve the browser to do it in Mathematica, I was not clear on this point. The reason is that no ready made implementation of the required RSA SHA-256 encryption exists, so one has to implement that first if one wants to do it without using other languages or tools. Preamble From what I can tell, it's not possible to authorize with Google Data without involving the browser at some point. Among the different oAuth 2.0 flows that Google offers, I find the flow intended for devices the most suitable one for integration with Mathematica . In essence, it works like this: The user visits the API console and registers his application. Google provides the user with a "client ID" and a "client secret". The application sends a request using the client ID. This request includes information about what kind of privileges the application needs. Google returns a code. When the user visits a certain URL and enters the code he will be able to review the list of privileges that the application requests. He then has to click a button to authorize the application to retrieve such information as is granted by those privileges. The application pings Google regularly to find out whether it has been authorized. At the moment that it's been authorized, Google returns a so called "access token" which can be used to send requests to the Google Data APIs. Authorization with Mathematica Since you cannot authorize once and be done with it (well... see "words of warning" about refresh tokens), but rather have to authorize every time you need to use the APIs, it's important that the process of authorization is not too cumbersome. I've implemented my solution as a package with a graphical user interface to make it as smooth as possible. Here's how it looks: The workflow mirrors the list in the preamble. At first, only the top form will be shown. Upon sent request, the two bottom boxes will appear. As the user visits the verification URL and enters the user code, Google will authorize the application. The package pings Google at the interval recommended by Google, and when the application is authorized the bar stops moving and the text changes, as can be seen, to "We're now authorized." At this point, we may acquire the access token like this: GoogleOAuthAccessKey[] access-key... Installing the package Download the package Put it somewhere and use Get (aka << ): << "~/Documents/Mathematica/GOAuth.m" Start the process using GoogleOAuth[] Words of warning The package does not attempt to deal with any errors that may arise. If it does not work, the best thing you can do is to restart the kernel and try again and make sure you have your credentials absolutely right. The time expiration on an access token appears to be, at the time of writing, one hour. If you need to use the API for prolonged periods of time, the best way to keep the session alive is not authorize manually over and over. Rather, you want to use refresh tokens . I didn't implement this, but those who have such needs can easily extend the package! About the technology behind the curtain I'd like to share some of the code, which is not related to the GUI, to shine some light on the process. For those who don't want to use the GUI and those who wants to understand how it works. The first call to acquire the user code looks like this: data = URLFetch[
"https://accounts.google.com/o/oauth2/device/code",
Method -> "POST",
"Parameters" -> {
"client_id" -> clientID,
"scope" -> scope
}
];
{deviceCode, expiresIn, interval, userCode,
verificationURL} = {"device_code", "expires_in", "interval",
"user_code", "verification_url"} /. ImportString[data, "JSON"]; As you can see, the data is returned as a JSON string. This goes for all Google Data API responses, so it's good to be aware of. This request will check if we've been authorized: tokens = URLFetch["https://accounts.google.com/o/oauth2/token",
Method -> "POST",
Parameters -> {
"client_id" -> clientID,
"client_secret" -> clientSecret,
"code" -> deviceCode,
"grant_type" -> "http://oauth.net/grant_type/device/1.0"
}
];
{accessToken, tokenType, accessExpiresIn, idToken,
refreshToken} = {"access_token", "token_type", "expires_in",
"id_token", "refresh_token"} /. ImportString[tokens, "JSON"]; If we haven't been authorized, the response will contain none of that information. Instead, it will only contain the element "error". The package looks for this to determine whether we've been authorized or not. The package keeps making this request every five seconds, as is currently recommended by Google, until we've been authorized. Scopes and an example query This query will obtain information about the user account: URLFetch["https://www.googleapis.com/oauth2/v1/userinfo?access_token=" <> accessToken] Whether or not we're allowed to request this information depends on what scope/privileges we requested to begin with. A suitable scope for this request is https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile I will not delve into the specifics of scopes. I will not attempt to implement the Google Data Spreadsheet API, either. That way, this answer is agnostic as to which Google Data API is to be used. This package and this answer provides the first step of how to authorize with Google Data using Mathematica , for all the rest the official Google documentation should be used. It has recently, long after I wrote this answer, come to my attention that using the "device flow" as this method does is currently not allowed for all Google APIs. So if it doesn't work for you with the specific API you had in mind, try to search on Google to see if other have also had problem while using the device flow for authorization.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/30748",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5369/"
]
}
|
30,751 |
I'm trying to ilustrate the difficulties in assigning bins to a data set and then running a comparison of the bins against a binomial distribution for all values- n, p. The code I have so far is (mostly thanks to Nasser): Manipulate[Show[Histogram[dataB, {-0.5, 7.5, c}, "PDF"],
DiscretePlot[PDF[BinomialDistribution[n, p], x], {x, 0, 20},
PlotStyle -> PointSize[Large]], ImagePadding -> All],
{{c, 8, "Column Width"}, 0, 4, .1, Appearance -> "Labeled"},
{{n, 7, "Number Of Quarters"}, 1, 20, 1, Appearance -> "Labeled"},
{{p, 0.5, "Fair Coin Toss"}, 0, 1, 0.01, Appearance -> "Labeled"}] The remaining problem, scaling the number of quarters in the binomial to the width of the X axis. Right now my X axis ranges from 0 to 7.5 in agreement with the range of the numbers in my data set. I think I need two X axes. One to illustrate the range of the numbers in my data set. And a second X axis to illustrate the number of quarters in the binomial ensemble (1 to 20). That's what I think. @Nasser
|
Update If I were to do this today, I would probably use Google's SDK for Java and JavaLink, which would allow for a better solution. Some have asked me why I said that we have to involve the browser to do it in Mathematica, I was not clear on this point. The reason is that no ready made implementation of the required RSA SHA-256 encryption exists, so one has to implement that first if one wants to do it without using other languages or tools. Preamble From what I can tell, it's not possible to authorize with Google Data without involving the browser at some point. Among the different oAuth 2.0 flows that Google offers, I find the flow intended for devices the most suitable one for integration with Mathematica . In essence, it works like this: The user visits the API console and registers his application. Google provides the user with a "client ID" and a "client secret". The application sends a request using the client ID. This request includes information about what kind of privileges the application needs. Google returns a code. When the user visits a certain URL and enters the code he will be able to review the list of privileges that the application requests. He then has to click a button to authorize the application to retrieve such information as is granted by those privileges. The application pings Google regularly to find out whether it has been authorized. At the moment that it's been authorized, Google returns a so called "access token" which can be used to send requests to the Google Data APIs. Authorization with Mathematica Since you cannot authorize once and be done with it (well... see "words of warning" about refresh tokens), but rather have to authorize every time you need to use the APIs, it's important that the process of authorization is not too cumbersome. I've implemented my solution as a package with a graphical user interface to make it as smooth as possible. Here's how it looks: The workflow mirrors the list in the preamble. At first, only the top form will be shown. Upon sent request, the two bottom boxes will appear. As the user visits the verification URL and enters the user code, Google will authorize the application. The package pings Google at the interval recommended by Google, and when the application is authorized the bar stops moving and the text changes, as can be seen, to "We're now authorized." At this point, we may acquire the access token like this: GoogleOAuthAccessKey[] access-key... Installing the package Download the package Put it somewhere and use Get (aka << ): << "~/Documents/Mathematica/GOAuth.m" Start the process using GoogleOAuth[] Words of warning The package does not attempt to deal with any errors that may arise. If it does not work, the best thing you can do is to restart the kernel and try again and make sure you have your credentials absolutely right. The time expiration on an access token appears to be, at the time of writing, one hour. If you need to use the API for prolonged periods of time, the best way to keep the session alive is not authorize manually over and over. Rather, you want to use refresh tokens . I didn't implement this, but those who have such needs can easily extend the package! About the technology behind the curtain I'd like to share some of the code, which is not related to the GUI, to shine some light on the process. For those who don't want to use the GUI and those who wants to understand how it works. The first call to acquire the user code looks like this: data = URLFetch[
"https://accounts.google.com/o/oauth2/device/code",
Method -> "POST",
"Parameters" -> {
"client_id" -> clientID,
"scope" -> scope
}
];
{deviceCode, expiresIn, interval, userCode,
verificationURL} = {"device_code", "expires_in", "interval",
"user_code", "verification_url"} /. ImportString[data, "JSON"]; As you can see, the data is returned as a JSON string. This goes for all Google Data API responses, so it's good to be aware of. This request will check if we've been authorized: tokens = URLFetch["https://accounts.google.com/o/oauth2/token",
Method -> "POST",
Parameters -> {
"client_id" -> clientID,
"client_secret" -> clientSecret,
"code" -> deviceCode,
"grant_type" -> "http://oauth.net/grant_type/device/1.0"
}
];
{accessToken, tokenType, accessExpiresIn, idToken,
refreshToken} = {"access_token", "token_type", "expires_in",
"id_token", "refresh_token"} /. ImportString[tokens, "JSON"]; If we haven't been authorized, the response will contain none of that information. Instead, it will only contain the element "error". The package looks for this to determine whether we've been authorized or not. The package keeps making this request every five seconds, as is currently recommended by Google, until we've been authorized. Scopes and an example query This query will obtain information about the user account: URLFetch["https://www.googleapis.com/oauth2/v1/userinfo?access_token=" <> accessToken] Whether or not we're allowed to request this information depends on what scope/privileges we requested to begin with. A suitable scope for this request is https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile I will not delve into the specifics of scopes. I will not attempt to implement the Google Data Spreadsheet API, either. That way, this answer is agnostic as to which Google Data API is to be used. This package and this answer provides the first step of how to authorize with Google Data using Mathematica , for all the rest the official Google documentation should be used. It has recently, long after I wrote this answer, come to my attention that using the "device flow" as this method does is currently not allowed for all Google APIs. So if it doesn't work for you with the specific API you had in mind, try to search on Google to see if other have also had problem while using the device flow for authorization.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/30751",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/8480/"
]
}
|
31,221 |
I can plot an ordinary histogram with blue shading and black borders like this: T = RandomVariate[NormalDistribution[0, 1], 10000];
Histogram[T, 30] And I can simulate hatching like this: T = RandomVariate[NormalDistribution[0, 1], 10000];
Histogram[T, 30, ChartElements -> Graphics[{Black, Line[{{0, 0}, {1, 1}}]}]] How can I get the hatching and the black borders at the same time?
|
I was sure Histogram can be modified to have the hatching style. Little late but what about this! g[{{xmin_, xmax_}, {ymin_, ymax_}}, ___] := Module[{yval, line},
yval = Range[ymin, ymax, 15];
line = Line /@ Transpose@{Most@({xmin, #} & /@ yval),Rest@({xmax, #} & /@ yval)};
{FaceForm[White],Polygon[{{xmin, ymin}, {xmax, ymin}, {xmax, ymax}, {xmin, ymax}}],
Orange, line}];
T = RandomVariate[NormalDistribution[0, 1], 10000];
Histogram[T, 30, ChartElementFunction -> g,
ChartBaseStyle -> EdgeForm[{Thin, Darker@Orange}], Frame -> True] Check in the function where yval is defined with Range[ymin, ymax, 15] one can change the $15$ to change the amount of hatching. You also have total control of the Graphics primitive used in the ChartElementFunction so you can use many more Directive for example Opacity and all. BR
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31221",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9231/"
]
}
|
31,257 |
I am trying to plot wind rose in Mathematica , but have no idea how to do this. Any suggestions ?
|
Edit : PolarTicks uses the built-in option for "Direction". An earlier version of this answer shows how to manually add PolarTicks . The following displays the wind rose on the right (with different data points). As rcollyer notes, the data points and joining lines can be both achieved in a single use of ListPolarPlot through PlotMarkers->Automatic . The PlotLabel is from Kuba. r = Table[{2 t Pi/16, RandomReal[{1, 6}]}, {t, 0, 15}];
ListPolarPlot[Append[r, r[[1]]],
PlotLabel -> "风向图", BaseStyle -> 14,
PolarTicks -> {"Direction", Automatic},
Joined -> True, PlotMarkers -> Automatic,
PlotStyle -> {PointSize[Large]}, PolarAxes -> True,
PolarGridLines -> {Table[2 k Pi/16, {k, 0, 15}], Automatic},
PolarAxesOrigin -> {Pi/2, 6}]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31257",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7050/"
]
}
|
31,385 |
For example, given list = {{1, -3, -5}, {2, 1, 6}, {0, 2, 4}, {-9, 2, 6}} should return: {-5, 6, 4, -9} Updated I found a undocumented function called Internal`MaxAbs ,but it only accept two args,for example: Internal`MaxAbs[2, -3]
Internal`MaxAbs[{1, -3, -5}, {2, 1, 6}]
(*
3
{2, 3, 6}
*) How can I make it can accept multiple parameters?
|
(Edited with a slight tweak for a tiny bit more speed) For the non-duplicate version I am finding this quite fast: f = If[+## > 0, ##] & @@ {Max[#], Min[#]} &
f /@ list
(* {-5, 6, 4, -9} *)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31385",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7339/"
]
}
|
31,745 |
In Mathematica there is a seemingly never-ending list of parameters that affect the appearance of Graphics and Graphics3D objects: ImageSize , ImageSizeRaw , ImagePadding , ImageMargins , PlotRange , PlotRangePadding , PlotRangeClipping , PlotRegion , ... I'm looking for a chart that illustrates as many of these parameters as possible in one place. What I'm looking for is something in the same spirit as this chart illustrating similar terminology for CSS3:
|
I doubt you can find a chart for all options, but take a look at this: For this and other insights two courses by Yu-Sung are a must (there are notebooks and videos there): Graphics Language Quick Start Visualization: Advanced 3D
Graphics The above chart is from the 1st one. The one @Kuba links in the comment to your question is from the 2nd - I show image below:
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31745",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2464/"
]
}
|
31,751 |
I compute all eigenvalues of a large matrix, and I decide that the speed is more important than the precision. Then the question is, can I speed up Eigenvalues[] by setting a lower precision goal? For example, consider a real symmetric random $100\times 100$ matrix: In[1]:= A = # + Transpose[#] &@RandomReal[{-1, 1}, {100, 100}]; and compute In[2]:= Do[Eigenvalues[A], {10}]; // AbsoluteTiming
Out[2]= {0.019001,Null} In real computation I may use a matrix much larger than $100\times 100$, and the computation would take much longer time than $0.019$ seconds. I want to speed up the computation. Can I set a lower precision goal, say 3 , so that Eigenvalues[] runs fuster? So I tried In[3]:= Do[Eigenvalues[SetPrecision[A, 3]], {10}]; // AbsoluteTiming
Out[3]= {12.358707,Null} The precision of the results is 3 , but the computation took 12.36 seconds. This is not what I want. Is there a clever way to speed up Eigenvalues[] by setting precision goal to be 3 ?
|
I doubt you can find a chart for all options, but take a look at this: For this and other insights two courses by Yu-Sung are a must (there are notebooks and videos there): Graphics Language Quick Start Visualization: Advanced 3D
Graphics The above chart is from the 1st one. The one @Kuba links in the comment to your question is from the 2nd - I show image below:
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31751",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/4684/"
]
}
|
31,804 |
Is there a simple way to copy mathematical expressions between Mathematica and Maple (or at least in one direction)? I mean only expressions built from numbers and predefined mathematical functions, whithout any patterns or programmatical constructs like Function , Map or Nest . Ideally, I want functions with different definitions to be automatically adjusted, for example the Mathematica expression EllipticF[Pi/6, 1/4] should be converted to the Maple expression EllipticF(1/2, 1/2) .
|
I assume you have Maple to use. If so, Simply open Maple and type the Mathematica command itself directly into Maple using the FromMma package built-into Maple, like this: restart;
with(MmaTranslator); #load the package
(*[FromMma, FromMmaNotebook, Mma, MmaToMaple]*) and now can use it FromMma(`Integrate[Cos[x],x]`); One can also use Maple convert command with the FromMma option, like this: convert(`Integrate[Cos[x],x]`, FromMma); For your example: FromMma(`EllipticF[Pi/6, 1/4]`); You can also use a Mathematica computational expression, not just single commands, like this, and then use the resulting Maple command inside Maple: r:=convert(`Table[i,{i,10}];`, FromMma);
(* r := [seq(i, i = 1 .. 10)] *) Now run the result in Maple: r;
(*[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]*) see http://www.maplesoft.com/support/help/Maple/view.aspx?path=MmaTranslator for information on the MmaTranslator package. For translating Maple back to Mathematica: The only program I know about that converts Maple to Mathematica is http://library.wolfram.com/infocenter/Conferences/5397 From Maple 9 Worksheets to Mathematica Notebooks by Yves Papegay. However, I can't find the actual program or the software. You can try to contact the author on this. This was from The 2004 Wolfram Technology Conference.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31804",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7288/"
]
}
|
31,837 |
Consider the following typical interactive sequence. First I produce a ListPlot : OK, not bad, but I want those dots to be bigger, and also joined. First, I make the dots bigger, like this: Good. Next, to join the dots, I do this: Aaaarrrrrgh! The dots disappeared! Why??? Don't they know anything about usability at WRI? I have tried to achieve the desired effect in a bazillion ways, and they all fail for one reason or another: either the dots no longer look like dots (but rather like diamonds, squares, triangles), or they are no longer the same color as the lines joining them, or something else... So my question is: how can I achieve the simple effect of several plots of (distinctly visible) dots joined by lines, and each plot of a different, but uniform, color? I also have a meta-question: The frustration illustrated by the interaction above is entirely typical of my experience with Mathematica , since day 1. I used to think that the reason why I had such difficulty getting the simplest things done with Mathematica was that I just didn't know it well enough... But this problem has persisted over the years, with hardly any improvement, even though I've devoted considerable effort to learning more and more about Mathematica . I have been using Mathematica now for about 20 years (!), and I still struggle for hours at a time with trivialities like this one. This makes me wonder whether these difficulties are really more a reflection with a fundamental flaw in some aspect of Mathematica 's design (one that somehow makes conceptually simple things turn out to be disproportionately difficult). Sure, when one is starting out with some new software simple things may take a long time to accomplish, but Mathematica is the only software that I've been using for more than, say 4-5 years, and that I still have to struggle with for hours to get simple things to work (and very often I just have to give up with)...
|
The PlotMarkers option is designed to handle this problem. Here are two very simple ways to do it using that option. data = Table[Table[Sin[k x], {x, 0, 2 Pi, 0.1}], {k, {1, 2, 3}}];
ListPlot[data,
Joined -> True,
PlotMarkers -> {Automatic, 7}] The above solution has a drawback: there can be a slight misalignment of the markers, because they're rendered as text. See this question for a detailed discussion. ListPlot[data,
Joined -> True,
PlotMarkers -> Graphics@{Disk[{0, 0}, [email protected]]}] Note: it might seem that wrapping Disk with List is unnecessary, but that is not the case. Without the wrapper, the points will alll be black. See this question for more detail.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31837",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2464/"
]
}
|
31,932 |
As one learns from a course on data structures, hash maps or dictionaries can be efficient when applied to appropriate tasks. I need a hash map in Mathematica and I've never found it. I'm scratching in one of my notebooks files, and I find myself still using the following code ( Leonid Shifrin ) to simulate this data structure. ClearAll[linkedList, toLinkedList, fromLinkedList, addToList, pop, emptyList];
SetAttributes[linkedList, HoldAllComplete];
toLinkedList[data_List] :=
Fold[linkedList, linkedList[], data];
fromLinkedList[ll_linkedList] :=
List @@ Flatten[ll, Infinity, linkedList];
addToList[ll_, value_] := linkedList[ll, value];
pop[ll_] := Last@ll;
emptyList[] := linkedList[];
ClearAll[makeHash];
makeHash[] := Module[{hash},
hash[_] := emptyList[];
hash /: add[hash, key_, value_] := ash[key] = addToList[hash[key], value];
hash /: get[hash, key_] := fromLinkedList@hash[key];
Return[hash]]; I was wondering if any of you had needed a dictionary. If you have, I would like know how you implemented it. I'm interested to use a map<string, int> .
|
Update: Mathematica version 10 introduced the builtin Association data structure (see tutorial and answer below ), which has most important features of dictionaries. Mathematica has no obvious hash-table structure but what most people forget is, that the DownValues of symbols, which means the simple, always-used function definitions, are implemented using hashing. Therefore, the most straightforward way to create a dictionary from string to integer is by making definitions: dict["hello"] = 1;
dict["blub"] = 2; By setting a definition for dict[___] you can create a default rule, when the key is not in the dictionary. Another thing you should look into is Dispatch , which generates an optimized dispatch table representation of a list of rules. There hashing is used too and you can build your dictionary on a list of rules like {"hello" -> 1, "blub" -> 2, ... } Indeed, the documentation suggests, that's exactly this what is used to speed up function definitions: Lists of rules produced by assignments made with = and := are automatically optimized with dispatch tables when appropriate. As pointed out by Faysal in his comment, please review the following Q&A: Struct equivalent in Mathematica?
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31932",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7251/"
]
}
|
31,948 |
I have a bunch of data points in the form of {latitude, longitude} . How can I plot their density on a US map? Single points on the map do not clearly show their distribution, so I'd like it to be a density map or something clearer. Please suggest. Note from Vitaliy Kaurov : this subject is also applicable to any geographic map (not necessarily US) and also to contour plots and general heat maps (besides density plots).
|
Update (15 FEB 2017) In the light of new geo-functionality developments I would like to add another approach via GeoImage . Consider the magnitude of the geomagnetic field across the entire planet. Get the data: data = QuantityMagnitude[
GeomagneticModelData[{{-90, -180.}, {90, 180.}}, "Magnitude",
GeoZoomLevel -> -2]]; Build high-res contour plot: plot = ListContourPlot[data, PlotRangePadding -> 0,
ColorFunction -> "TemperatureMap", Frame -> False,
InterpolationOrder -> 2, ImageSize -> 800, Contours -> 20,
ContourStyle -> Opacity[.2]] Specify how you would like to place this rectangle on the map (we use world range to show the application of geo-projection too): GeoGraphics[{GeoStyling[{"GeoImage", plot},
GeoRange -> {{-90, 90}, {-180, 180}}], Opacity[0.6],
GeoBoundsRegion["World"]}, GeoRange -> "World",
GeoProjection -> "Robinson"] Colored background interferes with colors of the heat map. Use just coastlines: GeoGraphics[{
GeoStyling[{"GeoImage", plot},
GeoRange -> {{-90, 90}, {-180, 180}}], Opacity[.8],
GeoBoundsRegion["World"]}, GeoRange -> "World",
GeoProjection -> "Robinson", GeoBackground ->
{"Coastlines", "Land" -> White, "Ocean" -> White, "Border" -> Black}] Older versions Well I do not have your data, so I'll just show things I have. I'll go with India, it has nice cities layout. You can upgrade for your data yourself. If you know only locations of cities, but not their population, then data = DeleteCases[
Reverse[CityData[#, "Coordinates"]] & /@ CityData[{All, "India"}],
Missing["NotAvailable"]];
Show[SmoothDensityHistogram[data, .3, ColorFunction -> "SunsetColors",
PlotPoints -> 150, Mesh -> 20, MeshStyle -> Opacity[.1], PlotRange -> All],
Graphics[{FaceForm[], EdgeForm[Directive[White, Opacity[.7]]],
CountryData["India", "Polygon"]}]] If you know the population, then maybe something like this: Graphics[{Opacity[0.1, Blue],
Cases[Disk[Reverse[CityData[#, "Coordinates"]],
Log[10.^12, CityData[#, "Population"]]] & /@
CityData[{All, "India"}], Disk[{__Real}, _Real]], {FaceForm[],
EdgeForm[Directive[Red, Thick, Opacity[.9]]],
CountryData["India", "Polygon"]}}, Background -> Black] For US use something like: data = DeleteCases[Reverse[CityData[#, "Coordinates"]] & /@
CityData[{All, "UnitedStates"}], Missing["NotAvailable"]];
Show[SmoothDensityHistogram[data, .5, ColorFunction -> "SunsetColors",
PlotPoints -> 150, Mesh -> 20, MeshStyle -> Opacity[.1], PlotRange -> All],
Graphics[{FaceForm[], EdgeForm[Directive[White, Opacity[.7]]],
CountryData["UnitedStates", "FullPolygon"]}],
AspectRatio -> Automatic, PlotRange -> {{-180, -65}, {20, 70}},
ImageSize -> 800, Frame -> False]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31948",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/402/"
]
}
|
31,985 |
I'm new to Mathematica and I spent the last hour trying to make the expression expression =
3 + 2 cos[t] + 3 cos[2t] + 5 cos[3t] + 7 cos[4t] + 9 sin[t] + 4 sin[3t] + 5 sin[4t] into a function of t . I tried f[t_] := expression but it didn't work.
|
Evaluate is your friend expression =
3 + 2 Cos[t] + 3 Cos[2 t] + 5 Cos[3 t] + 7 Cos[4 t] + 9 Sin[t] +
4 Sin[3 t] + 5 Sin[4 t];
f[t_] := Evaluate[expression];
f[0] 20 Edit:
This is the same as f[t_] = expression;
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31985",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9437/"
]
}
|
31,997 |
I currently work on an image segmentation scenario to detect cell nuclei in 3D using Mathematica . The data I have are image stacks in the TIFF file format. I would like to keep the sequence of image processing steps as small and simple as possible, since I expect the segmentation pipeline to work for several image stacks. I uploaded an example image stack containing several cell nuclei objects. Here is a screenshot of the image stack after creating an Image3D object out of it. smallCropped = Image3D[Import["...\\smallExample.tif"],
Axes -> True, AxesLabel -> {"X", "Y", "Z"}] The image shows about 40-50 cell nuclei objects. Note that due to a different spacings in the z-dimension the objects appear flattened. However, this should not have any influence on the segmentation itself. If you have a look at the data you will find out that the signal to noise ratio ( SNR ) is very high. The segmentation of the cell nuclei objects should therefore be feasible. Here is a GIF animation of the image stack moving through the stack in the z-dimension: I applied what seems to me as the most straight forward approach to segmentation in Mathematica ( Binarize and MorphologicalComponents ): Show[#, ImageSize -> 512] & /@ {binary = Binarize@smallCropped,
Image3D[Colorize@MorphologicalComponents@binary]} So far so good. As you can see from the colorized components matrix on the left, several cell nuclei objects are assigned the same object label ( e.g. the large pink object). Hence, preprocessing steps and a more sophisticated segmentation procedure seem to be required. After going through many types of image filtering and segmentation in Mathematica I got lost at some point and ended up plugging together various different filtering and segmentation steps. In most of the cases, the more I tried the worse the results got ;) I know that there is no golden rule for segmentation in image processing but the task of correctly segmenting the objects in this scenario seems to me not that difficult and I wonder if there exists a nice and easy way. The WatershedComponents method tries to separate connected objects. Since this method currently only works in 2D in Mathematica I implemented a method that first segments all the images of the stack slice by slice using a combination of GradientFilter , WatershedComponents , Binarize , MaxDetect and DistanceTransform . I then tried to merge the results from this 2D segmentation to end up with a 3D components matrix. I didn't put the code here but you can see the output of these two steps below (left: 2D WatershedComponents result, right: 3D result after merging). compsMatrix =
SelectComponents[
WatershedComponents[GradientFilter[#, 1],
MaxDetect[DistanceTransform@Binarize@ImageAdjust@#],
Method -> {"MinimumSaliency", .3}], "Count",
10 < # < 2000 &] & /@ Image3DSlices[Binarize@smallCropped] This is where I am at so far. The segmentation accuracy and object separation still looks poor to me and I am curious what steps might improve the results. My questions are: 1. What preprocessing steps (e.g. filters) built in Mathematica might
be suitable to increase the segmentation accuracy in this case? Is there a combination of standard filters that might work here? 2. How could I improve the separation of objects in 3D? 3. What about WatershedComponents for Image3D objects? Edit: response comment on Erosion A suggestion in the comments was to use Erosion . I know that erosion helps to separate objects.however, in this scenario it did not help and I would lose much information about the objects. Edit: response to answer by UDB Thanks to the nice approach proposed by UDB I could go on with the 3D segmentation problem and try the approach with my data. At first the results looked very promising but when taking a closer look, I have to say that the solution proposed does not provide a satisfying result. I have checked the results for the test image stack provided above I then used the functions proposed by UDB : distcompiled =
Compile[{{dist, _Integer, 3}},
Module[{dimi, dimj, dimk, disttab, i, j, k,
ii}, {dimi, dimj, dimk} = Dimensions[dist];
disttab = Table[(i - ii)^2, {ii, dimi}, {i, dimi}];
Table[
Min@Table[disttab[[i, ii]] + dist[[ii, j, k]], {ii, dimi}], {i,
dimi}, {j, dimj}, {k, dimk}]], CompilationTarget -> "C"];
Options[EuclideanDistanceTransform3D] = {Padding -> 1};
EuclideanDistanceTransform3D[im3d_Image3D, OptionsPattern[]] :=
Module[{dist3d, i, j, k, ii, dimi, dimj, dimk},
dist3d =
Developer`ToPackedArray@
ParallelMap[
Round[ImageData[
DistanceTransform[#, DistanceFunction -> EuclideanDistance,
Padding -> OptionValue[Padding]]]^2] &,
Image3DSlices[
Image3D[ArrayPad[ImageData[im3d, "Bit"], 1,
Padding -> OptionValue[Padding]]]]];
If[OptionValue[Padding] != 0,
dist3d =
Developer`ToPackedArray@
ParallelMap[
If[Times @@ Dimensions[#] == Total[Flatten[#]], # +
1073741822, #] &, dist3d, {1}];];
dist3d = Developer`ToPackedArray@distcompiled[dist3d];
dist3d = ArrayPad[dist3d, -1];
Image3D[Sqrt@dist3d, "Real"]]; As you can see, I changed the CompilationTarget to "C" and added a missing comma after the local variable disttab in the distcompiled function. I then packed the function together and gave it a name: splitSegmentation3D[img3d_Image3D] :=
Function[{image},
Image3D[Colorize[
MorphologicalComponents[
ImageMultiply[
Binarize[
LaplacianGaussianFilter[
EuclideanDistanceTransform3D[
ColorNegate[
Binarize[
ImageMultiply[MaxDetect[#], #] &[
EuclideanDistanceTransform3D[image]], 5]]], 1]],
image]]]]][img3d] As proposed I set the threshold for accepted maxima to 5 in this function. For binarization I use the proposed TotalVariationFilter as pre-processing step and then do a simple Binarize . I then do the last of the pipeline using the function splitSegmentation3D : {smallCropped = Image3D[Import["...\\smallExample.tif"],
prepro = TotalVariationFilter[smallCropped],
bin = Binarize[prepro],
comps = splitSegmentation3D[Binarize[prepro]]} The components image looks just like the components image in the answer except for the colors...good. But when taking a closer look at the segmentation by slicing through the images in z-dimension, you see the details. I put the results of the complete image processing chain next to each other (from left to right: original, preprocessed, binary, components image): I see multiple problems with this approach. First, using TotalVariationFilter as preprocessing step also blurs the image which results in many connected objects. Second, the splitting performs heavy over segmentation resulting in splitted objects. Third, many objects seem to be rounded by the segmentation. I think this results from the EuclideanDistanceTransform3D in combination with ImageMultiply . I don't think that a perfect segmentation is possible on my data, but it should work out for at least some of the objects.
|
Introduction I propose a solution to this object separation problem, which simply was inspired by one of the application examples of DistanceTransform . It uses a simple method to split virtually connected (blurred) objects in 3D. A LoG filter (Marr-Hildreth operator) is detecting edges in the Euclidean distance transform by this doing a tesselation required to split the abovementioned blurred objects. Since the DistanceTransform function presently is lacking 3D functionality, an own implementation of Euclidean distance transform is provided. Using this method you might end up with this label image: But one step after another. This is our test data set for the moment: img3d = Image3D[
ArrayPad[DiskMatrix[{3, 4, 5}], {{5, 10}, {20, 15}, {25, 30}}] +
ArrayPad[DiskMatrix[{5, 6, 3}], {{3, 8}, {18, 13}, {33, 26}}]] A self-made 3D distance transform However, we still have to have a 3D distance transform. I will provide a poor man's solution of a 3D Euclidean distance transform, utilizing the built-in 2D DistanceTransform and adding some stuff according to algorithm 1 of the 1994 Pattern Recognition paper by Saito and Toriwaki entitled "New algorithm for Euclidean distance transformation of an n-dimensional digitized picture with applications" , vol. 27, no. 11, pp. 1551-1565. The following code provides an auxiliary function later on used to do the Euclidean distance measurements in the third dimension. It receives a 3D matrix dist consisting of a stack of 2D distance transformed images, whereas the squared Euclidean distances are assumed here. Along the stack direction, for each voxel it searches the minimum sum of the squared distance and the provided intermediate result: distcompiled = Compile[{{dist, _Integer, 3}},
Module[{dimi, dimj, dimk, disttab, i, j, k, ii},
{dimi, dimj, dimk} = Dimensions[dist];
disttab = Table[(i - ii)^2, {ii, dimi}, {i, dimi}];
Table[
Min[disttab[[i, All]] + dist[[All, j, k]]],
{i, dimi}, {j, dimj}, {k, dimk}]
],
CompilationTarget -> "WVM"
(*this might be set to "C" if a compiler is installed*)
]; What still has to be defined is the function EuclideanDistanceTransform3D itself: Options[EuclideanDistanceTransform3D] = {Padding -> 1};
EuclideanDistanceTransform3D[im3d_Image3D, OptionsPattern[]] :=
Module[{dist3d, i, j, k, ii, dimi, dimj, dimk},
dist3d =
Developer`ToPackedArray@
Map[Round[
ImageData[
DistanceTransform[#, DistanceFunction -> EuclideanDistance,
Padding -> OptionValue[Padding]]]^2] &,
Image3DSlices[
Image3D[ArrayPad[ImageData[im3d, "Bit"], 1,
Padding -> OptionValue[Padding]]]]];
If[OptionValue[Padding] != 0,
dist3d =
Developer`ToPackedArray@
Map[If[Times @@ Dimensions[#] == Total[Flatten[#]], # +
1073741822, #] &, dist3d, {1}];
];
dist3d = Developer`ToPackedArray@distcompiled[dist3d];
dist3d = ArrayPad[dist3d, -1];
Image3D[Sqrt@dist3d, "Real"]
]; This function assumes a binary Image3D handed over using the variable im3d . The first part of the function does nothing but splitting the 3D stack into a sequence of 2D images and mapping them into the DistanceTransform function, wheras the result is re-squared. A one-voxel padding is applied using the Padding option provided. The second part is circumventing the behavior of DistanceTransform when receiving images only consisting of 1's, in such a case it again returns an image purely filled with 1's, however, it should be full with Infinity entries, since there was not any 0. So we add $$2^{30}-2=1073741822$$ in such cases, by this ensuring that $$2^{31}-1$$ is never being exceeded as long as $$2^{15}=32768$$ is taken as largest extent in either of the volume dimensions: $$2^{30}-1+(2^{15})^2=2^{31}-1=2147483647$$. In the third part we just use the auxiliary function already defined above. In the fourth part the padding made in the beginning is being eliminated. In the last part an Image3D is being assembled as return value, whereas for all elements of dist3d the square root is extracted, since we want to provide the Euclidean distances. Now we have this EuclideanDistanceTransform3D . A first test Let us make a first test: EuclideanDistanceTransform3D[img3d] // ImageAdjust Well, we are interested in those voxels indicating the local maxima: MaxDetect[EuclideanDistanceTransform3D[img3d]] We might want to exclude some local maxima with not exceeding some certain distance values (3 in this example; this makes no difference to the result above for this test data set): Binarize[ImageMultiply[MaxDetect[#], #] &[EuclideanDistanceTransform3D[img3d]], 3] Using these local maxima voxels, we apply another EuclideanDistanceTransform3D to measure the distances from them (we need to negate the maxima voxel intermediate result): EuclideanDistanceTransform3D[
ColorNegate[
MaxDetect[EuclideanDistanceTransform3D[img3d]]]] // ImageAdjust What follows is the detection of 3D edges inside this second distance transform using an LoG filter: LaplacianGaussianFilter[
EuclideanDistanceTransform3D[
ColorNegate[MaxDetect[EuclideanDistanceTransform3D[img3d]]]],
1] // ImageAdjust By binarizing the latter we will obtain a template to tesselate our data set, so objects might be split as intended. Here is the full image processing chain: Function[{img3d},
Image3D[
Colorize[
MorphologicalComponents[
ImageMultiply[
Binarize[
LaplacianGaussianFilter[
EuclideanDistanceTransform3D[
ColorNegate[
Binarize[
ImageMultiply[
MaxDetect[#], #
] &[EuclideanDistanceTransform3D[img3d]],
3(*allow only maxima with distance values > 3*)
]
]
], 1(*LoG filter kernel size*)
]
], img3d
]
]
]
]
][img3d] A second test To apply this method to the smallCropped data set provided above, I recommend to do an edge-preserving smoothing before binarization: img3d = Binarize[TotalVariationFilter[smallCropped]] What simply has to be done here is to apply the same image processing chain given above, whereas the minimum threshold for accepted maxima was set to 5 here instead of 3 (as for the synthetic example). Please compare this output with the original data set: We are done. Problems I still see here may be mainly caused due to the non-convexity of a certain number of objects in this data set. Parallelized version of Euclidean 3D distance transform I am happy to show you a parallelized version of my self-made 3D distance transform. Again, we use a compiled auxiliary function to treat the 3rd dimension, but this time with two option set: RuntimeAttributes -> {Listable}, Parallelization -> True , so we later on will be able to hand over a series of 3D lists, and we have enabled the execution of these series in parallel: distcompiledparallelized = Compile[{{dist, _Integer, 3}},
Module[{dimi, dimj, dimk, disttab, i, j, k, ii},
{dimi, dimj, dimk} = Dimensions[dist];
disttab = Table[(i - ii)^2, {ii, dimi}, {i, dimi}];
Table[Min[disttab[[i, All]] + dist[[All, j, k]]], {i, dimi}, {j, dimj}, {k, dimk}]],
CompilationTarget -> "C",
(*this should be set to "WVM" if a compiler is not installed*)
RuntimeAttributes -> {Listable}, Parallelization -> True
]; Even though Wolfram virtual machine does a good job here, we have turned on C compilation. Now we come to the function itself: Options[EuclideanDistanceTransform3Dparallelized] = {Padding -> 1};
EuclideanDistanceTransform3Dparallelized[im3d_Image3D,
OptionsPattern[]] :=
Module[{dist3d, forwardtransposition, backwardtransposition,
addmargin},
backwardtransposition = Ordering[Reverse[ImageDimensions[im3d]]];
forwardtransposition = Ordering[backwardtransposition];
dist3d =
Developer`ToPackedArray@
Map[Round[
ImageData[
DistanceTransform[#, DistanceFunction -> EuclideanDistance,
Padding -> OptionValue[Padding]]]^2] &,
Image3DSlices[
Image3D[ArrayPad[
Transpose[ImageData[im3d, "Bit"], forwardtransposition], 1,
Padding -> OptionValue[Padding]]]]];
If[OptionValue[Padding] != 0,
dist3d =
Developer`ToPackedArray@
Map[If[Times @@ Dimensions[#] == Total[Flatten[#]], # +
1073741822, #] &, dist3d, {1}];
];
addmargin =
Ceiling[#1/#2]*#2 - #1 &[Dimensions[dist3d][[3]], $ProcessorCount];
dist3d = ArrayPad[dist3d, {{0, 0}, {0, 0}, {0, addmargin}}];
dist3d =
Function[{len, procs},
dist3d[[All,
All, # ;; Min[# + Ceiling[len/procs] - 1, len]]] & /@
Range[1, len, Ceiling[len/procs]]][
Last[Dimensions[dist3d]], $ProcessorCount];
dist3d = Developer`ToPackedArray@distcompiledparallelized[dist3d];
dist3d = Join[Sequence @@ dist3d, 3];
dist3d = ArrayPad[dist3d, {{-1, -1}, {-1, -1}, {-1, -addmargin - 1}}];
dist3d = Transpose[dist3d, backwardtransposition];
Image3D[Sqrt@N@dist3d, "Real"]
]; First of all we make sure that the 3D data will be transposed in a way that the extent of the 1st coordinate is smaller than the 2nd and 3rd, by this generally minimizing the computational load of distcompiledparallelized called later on. To manage this, we determine appropriate lists forwardtransposition and backwardtransposition for the respective Transpose calls later on. Then we do the processing of the series of 2D images as done in the initial version. Once this was done, we do some preparations for the parallelization. We have to make sure that all 3D sublists we want to hand over to distcompiledparallelized have the same dimensions. However, depending on the im3d dimensions and the $ProcessorCount this requires some padding. We do this padding solely at the upper margin of the 3rd dimension. Once we have done the padding, we continue with equally splitting dist3d depending on both its 3rd dimension and the $ProcessorCount , so distcompiledparallelized can be called. What remains to be done is some maintenance: Re-joining the dist3d , removing the margin (together with the overall padding), and undoing the transposition. The last very effective way for speeing up is to numericalize dist3d before drawing the square root ... A further approach to the object separation problem Looking on the smallCropped data set one might get the feeling that its height requires stretching in order to let the cells appear as spheres (anisotropy correction o f course will have some influence to our distance based approach), we may assume a factor of approx. 3: smallCroppedinterpolationfunction =
ListInterpolation[ImageData[smallCropped, "Real"], Method -> "Spline"];
smallCroppedinterpolated =
ParallelTable[
smallCroppedinterpolationfunction[i, j, k], {i, 1,
Dimensions[ImageData[smallCropped]][[1]], 0.33}, {j, 1,
Dimensions[ImageData[smallCropped]][[2]]}, {k, 1,
Dimensions[ImageData[smallCropped]][[3]]}];
smallCroppedstreched = Image3D[smallCroppedinterpolated, "Real"] Then we again should do a TV filtering, but for fluorescence data we better should assume a Poisson noise: img3d = Binarize[
TotalVariationFilter[smallCroppedstreched, Method -> "Poisson", MaxIterations -> 100]
] Without option specification (or by setting Method -> "Cluster" ) Binarize takes "Otsu's method" doing some minimization of the intra-class variances. The distance transformed img3d then looks like this: EuclideanDistanceTransform3Dparallelized[img3d] // ImageAdjust Having detected the maxima inside this distance transform (and selecting those exceeding a certain minimum), we can look how both the distance field between these maxima and the tesselation look like: EuclideanDistanceTransform3Dparallelized[ColorNegate[
Binarize[
ImageMultiply[MaxDetect[#], #] &[
EuclideanDistanceTransform3Dparallelized[img3d]],
15]]] // ImageAdjust LaplacianGaussianFilter[
EuclideanDistanceTransform3Dparallelized[ColorNegate[
Binarize[
ImageMultiply[MaxDetect[#], #] &[
EuclideanDistanceTransform3Dparallelized[img3d]], 15]]],
3] // ImageAdjust So, here is the code doing all the steps: Function[{im3d},
Image3D[
Colorize[
MorphologicalComponents[
ImageMultiply[
Binarize[
LaplacianGaussianFilter[(*Marr-Hildreth operator*)
EuclideanDistanceTransform3Dparallelized[
ColorNegate[
Binarize[
ImageMultiply[
MaxDetect[#], #
] &
[EuclideanDistanceTransform3Dparallelized[im3d]],
15(*allow only maxima with distance values > 15*)
]
]
], 3(*LoG filter kernel size*)
]
], im3d
]
]
]
]
][img3d] You may complain that small cells are missing, well, I did my best (mixed-sized cells in an object separation problem make things sophisticated), and you may play with the two parameters, i.e. the LoG filter kernel size and the minimum maxima threshold. I personally think that it should not be considered an artifact that almost all cells touching the data set margins have been canceled. Hope you enjoy the parallelized Euclidean 3D distance transform. It now can easily handle large volumes (not exceeding 32768 for all dimensions). If there is anybody who is inspired to extend my self-made 3D distance transform approach to ManhattanDistance and ChessboardDistance , please feel free to do so... Addition: Extended 3D Distance Transform I am happy to introduce my extended parallelized solution DistanceTransform3D for Image3D data, in analogy to the kernel function DistanceFunction presently only processing Image data, it now includes these distances: EuclideanDistance , ManhattanDistance , and ChessboardDistance . We utilize three different compiled auxiliary functions: eucldistcompiledparallelized = Compile[{{dist, _Integer, 3}},
Module[{dimi, dimj, dimk, disttab, i, j, k, ii},
{dimi, dimj, dimk} = Dimensions[dist];
disttab = Table[(i - ii)^2, {ii, dimi}, {i, dimi}];
Table[
Min[disttab[[i, All]] + dist[[All, j, k]]], {i, dimi}, {j,
dimj}, {k, dimk}]
],
CompilationTarget -> "C", (*should be set to "WVM" if no compiler is installed*)
RuntimeAttributes -> {Listable}, Parallelization -> True
];
manhdistcompiledparallelized = Compile[{{dist, _Integer, 3}},
Module[{dimi, dimj, dimk, disttab, i, j, k, ii},
{dimi, dimj, dimk} = Dimensions[dist];
disttab = Table[Abs[(i - ii)], {ii, dimi}, {i, dimi}];
Table[
Min[disttab[[i, All]] + dist[[All, j, k]]], {i, dimi}, {j,
dimj}, {k, dimk}]
],
CompilationTarget -> "C", (*should be set to "WVM" if no compiler is installed*)
RuntimeAttributes -> {Listable}, Parallelization -> True
];
chessdistcompiledparallelized = Compile[{{dist, _Integer, 3}},
Module[{dimi, dimj, dimk, disttab, i, j, k, ii},
{dimi, dimj, dimk} = Dimensions[dist];
disttab = Table[Abs[(i - ii)], {ii, dimi}, {i, dimi}];
Table[
Min@Map[Max[#] &,
Transpose[{disttab[[i, All]], dist[[All, j, k]]}]], {i,
dimi}, {j, dimj}, {k, dimk}]
],
CompilationTarget -> "C", (*should be set to "WVM" if no compiler is installed*)
RuntimeAttributes -> {Listable}, Parallelization -> True
]; The 3D distance transform reads now: Options[DistanceTransform3D] = {Padding -> 1, DistanceFunction -> EuclideanDistance};
DistanceTransform3D[im3d_Image3D, thresh_Real: 0., OptionsPattern[]] :=
Module[{dist3d, forwardtransposition, backwardtransposition, addmargin},
backwardtransposition = Ordering[Reverse[ImageDimensions[im3d]]];
forwardtransposition = Ordering[backwardtransposition];
Switch[OptionValue[DistanceFunction],
EuclideanDistance,
dist3d =
Developer`ToPackedArray@
Map[Round[
ImageData[
DistanceTransform[#,
DistanceFunction -> EuclideanDistance,
Padding -> OptionValue[Padding]]]^2] &,
Image3DSlices[
Image3D[ArrayPad[
Transpose[ImageData[Binarize[im3d, thresh], "Bit"],
forwardtransposition], 1,
Padding -> OptionValue[Padding]]]]];
,
_,
dist3d =
Developer`ToPackedArray@
Map[ImageData[
DistanceTransform[#,
DistanceFunction -> OptionValue[DistanceFunction],
Padding -> OptionValue[Padding]]] &,
Image3DSlices[
Image3D[ArrayPad[
Transpose[ImageData[Binarize[im3d, thresh], "Bit"],
forwardtransposition], 1,
Padding -> OptionValue[Padding]]]]];
];
If[OptionValue[Padding] != 0,
dist3d =
Developer`ToPackedArray@
Map[If[Times @@ Dimensions[#] == Total[Flatten[#]], # +
1073741822, #] &, dist3d, {1}];
];
addmargin = Ceiling[#1/#2]*#2 - #1 &[Dimensions[dist3d][[3]], $ProcessorCount];
dist3d = ArrayPad[dist3d, {{0, 0}, {0, 0}, {0, addmargin}}];
dist3d =
Developer`ToPackedArray@
Function[{len, procs},
dist3d[[All,
All, # ;; Min[# + Ceiling[len/procs] - 1, len]]] & /@
Range[1, len, Ceiling[len/procs]]][
Last[Dimensions[dist3d]], $ProcessorCount];
Switch[OptionValue[DistanceFunction],
EuclideanDistance,
dist3d = Developer`ToPackedArray@eucldistcompiledparallelized[dist3d];
,
ManhattanDistance,
dist3d = Developer`ToPackedArray@manhdistcompiledparallelized[dist3d];
,
ChessboardDistance,
dist3d = Developer`ToPackedArray@chessdistcompiledparallelized[dist3d];
];
dist3d = Join[Sequence @@ dist3d, 3];
dist3d = ArrayPad[dist3d, {{-1, -1}, {-1, -1}, {-1, -addmargin - 1}}];
dist3d = Transpose[dist3d, backwardtransposition];
Switch[OptionValue[DistanceFunction],
EuclideanDistance,
Return[Image3D[Sqrt@N@dist3d, "Real"]];
,
_,
Return[Image3D[dist3d, "Bit16"]];
];
]; We generate a synthetic data set: SeedRandom[2405];
img3d = Image3D[Table[If[RandomReal[] > N[1/1000], 1, 0], {10}, {20}, {15}]]; We do a short performance test: eucldist3d = DistanceTransform3D[img3d, DistanceFunction -> EuclideanDistance];
manhdist3d = DistanceTransform3D[img3d, DistanceFunction -> ManhattanDistance];
chessdist3d = DistanceTransform3D[img3d, DistanceFunction -> ChessboardDistance]; Here we have the results: ImageAdjust[ColorNegate[#]]& /@ {img3d, eucldist3d, manhdist3d, chessdist3d} Hope one day the same 3D functionality will be included in the built-in DistanceTransform .
|
{
"source": [
"https://mathematica.stackexchange.com/questions/31997",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2024/"
]
}
|
32,025 |
How one can measure the execution time (time that is spent for code to finish) of a program in Mathematica ? I understand that there are general timing functions ( Timing , AbsoluteTiming , TimeUsed , etc.) that can be used for measuring CPU or wall time, but I don't know the pros/contras (and caveats) of the different methods.
|
This question might be considered a duplicate. It is closely related to these: Considerations when determining efficiency of Mathematica code Difference between AbsoluteTiming and Timing Benchmarking expressions Profiling from Mathematica However, one simple reading of this question that I do not believe is covered in the answers above is answered with this Front End option : SetOptions[$FrontEndSession, EvaluationCompletionAction -> "ShowTiming"] This will print the total evaluation time for each cell as it completes in the lower left window margin: To make the setting persistent between sessions use $FrontEnd in place of $FrontEndSession . Update: "ShowTiming" was already covered in Brett's answer to: Does AbsoluteTiming slow the evaluation time?
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32025",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9390/"
]
}
|
32,043 |
The following examples only work for the first character of the whole string, but not of words. s = "words are lowercase";
StringJoin[MapAt[ToUpperCase, Characters[s], 1]] (* ==> "Words are lowercase" *)
StringReplacePart[#, ToUpperCase[StringTake[#, 1]], 1]&@s (* ==> "Words are lowercase" *) Is there any method along these lines to produce correct title case strings of the form: "Words Are Lowercase"
|
From the documentation , though IMHO not easy to find: StringReplace["this is a test", WordBoundary ~~ x_ :> ToUpperCase[x]] "This Is A Test" István Zachar highlighted a problem with WordBoundary that I'm still trying to understand. Nevertheless it seems that one can use: strAcc = "árv ízt űr őt ük örf úr óg ép";
StringReplace[strAcc, z : (StartOfString | WhitespaceCharacter ~~ _) :> ToUpperCase[z]] "Árv Ízt Űr Őt Ük Örf Úr Óg Ép" It appears that the PCRE library at least as used by Mathematica does not recognize certain characters as letters. A few examples: StringReplace[strAcc, z : RegularExpression["(?:\\A|\\s)."] :> ToUpperCase[z]]
StringReplace[strAcc, z : RegularExpression["\\b."] :> ToUpperCase[z]] "Árv Ízt Űr Őt Ük Örf Úr Óg Ép"
"Árv Ízt űR őT Ük Örf Úr Óg Ép" (* note odd handling *) StringCases["abcőű", RegularExpression["\\w"]] {"a", "b", "c"} (* ő and ű missing *)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32043",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6648/"
]
}
|
32,293 |
I'm trying to get the eigenvalues of a one dimensional time-independent Schrödinger equation, $-\frac{h^2}{2m_0}\frac{d^2\psi}{dx^2}+U(x)~\psi=Ei~\psi$ where U(x) is some potential and Ei is the eigen energy. I'm trying to find the Ei if given a potential U(x). For example, if U(x) is the harmonic potential $U(x)=\frac{1}{2}m_0\omega^2x^2$ then the solution for Ei would be $Ei=(n+\frac{1}{2})\hbar\omega$. Here is my try to solve a harmonic potential: There is a new function introduced in version 9 called ParametricNDSolveValue which can be used to solve parametric differential equations. In its advertisement , there is a demonstration of solving a similar eigenproblem of the finite potential well. There the energy is treated as a parameter, and then the Schrödinger is solved as a parameter of the energy. Then we select only the energies that make the wave function vanish at large distance, which is required by physics. Those selected energies are the eigen energy of the system. Here I use the same way. \[HBar] = e = m0 = 1.; ω = 1;
U[x_] := 1/2 m0 ω^2 x^2 The potential is symmetric, so that the wave function must be odd or even function. First if the wave function is odd, then it must goes through zero. pfun1 = ParametricNDSolveValue[{-(\[HBar]^2/(2 m0)) ψ''[x] +
U[x] ψ[x] == Ei ψ[x], ψ[0.] == 0., ψ[1.] ==
1.}, ψ, {x, -4, 4}, {Ei}] These are the solutions Show[Plot[U[x], {x, -5, 5}, PlotStyle -> Directive[Thick, Green]]
, Plot[Evaluate@Table[Re[pfun1[Ei][x]], {Ei, 0., 5., 0.5}], {x, -4,
4}], PlotRange -> {All, {-6, 10}}] The wave function value at -4 as a function of parameter Ei Plot[pfun1[Ei][-4], {Ei, 0, 5}, ImageSize -> Medium] We can select the energies which make the wave function goes to zero, those are the eigen energies. (Note that previously this just said val instead of val1, which gave an error down the road.) val1 = Map[
FindRoot[pfun1[Ei][-4], {Ei, #}] &, {1, 2, 3}]
(*{{Ei -> 1.50001}, {Ei -> 1.50001}, {Ei -> 3.50169}}*) Similarly, if the wave function is even, then the first derivative should be 0 at 0. pfun2 = ParametricNDSolveValue[{-(\[HBar]^2/(2 m0)) ψ''[x] +
U[x] ψ[x] == Ei ψ[x], ψ'[0.] == 0., ψ[1.] ==
1.}, ψ, {x, -4, 4}, {Ei}]
Show[Plot[U[x], {x, -5, 5}, PlotStyle -> Directive[Thick, Green]]
, Plot[Evaluate@Table[Re[pfun2[Ei][x]], {Ei, 0., 5., 0.5}], {x, -4,
4}], PlotRange -> {All, {-6, 10}}]
Plot[pfun2[Ei][-4], {Ei, 0, 5}, ImageSize -> Medium] The eigen energies can be selected in the same way val2 = Map[FindRoot[pfun2[Ei][-4], {Ei, #}] &, {1, 2, 3}]
(*{{Ei -> 0.5}, {Ei -> 2.5002}, {Ei -> 2.5002}}*) So finally the eigen energyies are eigenEv = val1 /. Rule[_, x_] -> x // Flatten;
eigenOd = val2 /. Rule[_, x_] -> x // Flatten;
Sort[Join[eigenEv, eigenOd]]
(*{0.5, 1.50001, 1.50001, 2.5002, 2.5002, 3.50169}*) eigen functions are Show[Plot[U[x], {x, -5, 5}, PlotStyle -> Directive[Thick, Green]]
, Plot[Evaluate@{Table[Re[pfun1[Ei][x]], {Ei, eigenEv}],
Table[Re[pfun2[Ei][x]], {Ei, eigenOd}]}, {x, -4, 4}],
PlotRange -> {All, {-3, 3}}] which basically agree with the analytical results. Questions : Are there other ways to find the eigen energies which are more efficient and accurate than the parameter methods? For example, in this case we can see that the fourth eigen energy should be exactly 3.5 but it gave 3.50169 which is quite a large error. Also in my real system, I'm interested in calculating up to the hundredth eigen energies, this method seems too slow to do that. If the potential U(x) is not symmetric, how do I set the initial or value? For example, in the harmonic potential case, we set ψ'[0]=0, ψ[1]=1 in the even case and ψ[0]=0, ψ[1]=1 in the odd case, in a more general potential, how do I set the initial or boundary value?
|
You asked for alternative approaches to what you did, so here is one: A completely different approach to the one-dimensional time-independent Schrödinger equation would be to use matrix techniques . The idea is to eliminate the need for NDSolve entirely. For bound-state problems, you can do this by choosing a basis satisfying the condition of vanishing wave function at infinity and expanding all quantities in that basis. A particularly nice way of doing this has been pointed out in: H. J. Korsch and M Glück, "Computing quantum eigenvalues made easy"
Eur. J. Phys. 23 (2002) 413-426. It uses the harmonic-oscillator basis, but also introduces the relation between position and momentum operators on one hand, and the harmonic-oscillator operators on the other hand. This makes it very useful as a teaching method. I implemented that approach here, with some refinements to satisfy given tolerances and make plots: The potential energy $U(x)$ is assumed to be a polynomial of finite degree in a single variable. Since we're using a harmonic-oscillator basis to find the eigenstates of the Hamiltonian, a finite-degree polynomial translates to a set of finite powers of the position matrix xOp . By increasing the dimension of these matrices while keeping the powers fixed to their finite values, we can achieve convergence of the energy eigenvalues and eigenvectors near the potential minimum. The larger the matrix dimension, the more of the low-lying eigenvalues will converge to the the true eigenvalues. First I define position and momentum operators in the basis of harmonic-oscillator eigenfunctions, and a matrix representing the kinetic energy. The dimension of the matrices is dim : Define basic matrices xOp[dim_] :=
SparseArray[{Band[{1, 2}] -> #, Band[{2, 1}] -> #}, {#, #} &@dim] &[
Table[Sqrt[i], {i, dim - 1}]/Sqrt[2]]
eKin[dim_] :=
1/2 SparseArray[{Band[{1, 1}] -> Table[i - 1/2, {i, dim}],
Band[{1, 3}] -> #, Band[{3, 1}] -> #}, {#, #} &@dim] &[
Table[-Sqrt[i (i + 1)/2], {i, dim - 2}]/Sqrt[2]] Spectrum and eigenfunctions This is the heart of the computation. The function called spectrum determines the eigenvalues and eigenvectors of a Hamiltonian with the above kinetic energy and a polynomial-type potential energy term. The number of eigenvalues to be returned is given as the first argument, n , and their maximum error is given by tolerance (the latter can be left out if the default value is sufficient): spectrum[n_, tolerance_: .00001][potential_, var_] /;
PolynomialQ[potential, var] := Module[
{
x, h, e, v,
c = CoefficientList[potential, var],
min = First@Check[
Minimize[potential, var],
Print[
"No absolute potential minimum found. Make sure the leading \
power has a positive coefficient!"];
Abort[],
Minimize::natt
]
},
FixedPoint[
{#[[1]] + 1,
Eigenvalues[
h = eKin[#[[1]]] +
N[Sum[c[[i]] MatrixPower[xOp[#[[1]]], i - 1], {i, 2,
Length[c]}] + (c[[1]] - min) IdentityMatrix[#[[
1]]]], -n]} &, {n + 1, 2 Reverse@Range[n] - 1},
SameTest -> (Max@Abs[#1[[2]] - #2[[2]]] < tolerance &)];
{e, v} = Reverse /@ Eigensystem[h, -n];
{e + min, ψe /@ v}
] The second set of arguments above ( potential , var ) are the potential energy U(x) and the name of the position variable - usually it would be x . I had to make a change for compatibility with Mathematica version 10 because it throws an error when you try to apply MatrixPower to a numerically singular matrix with power 0 . Position matrices can become numerically singular for large dimension, so I have to treat the zeroth power of xOp separately. This wasn't necessary in version 8. Since that term only determines a constant energy offset, it is lumped together with another constant term that I introduce in order to shift the potential minimum to zero (so that the Eigenvalues are sorted in ascending order, starting with the ground state - this shift by min is undone at the end of the calculation). Output results in position basis To get the wave function, we implement the sum over basis states to get the wave functions ψe (here, e doesn't have anything to do with parity - the method works independently of parity symmetry ). The output format is defined below to yield a shortened representation that doesn't spit out the entire list of coefficients, only listing their number. Format[ψe[l_List]] := ψe[
Row[{"\[LeftSkeleton]", Length[l], "\[RightSkeleton]"}]]
ψe[l_List][x_] := 1/(Pi^(1/4))Exp[-x^2/ 2] l.(1/Sqrt[2^# #!] HermiteH[#, x] &[Range[Length[l]] - 1])
plotSpectrum[data_, potential_, {var_, min_, max_}] :=
Show[
Apply[
Plot[
Evaluate[#1 + (Last[#1] - First[#1])/(2 + Length[#1])/
2 Through[#2[var]]], {var, min, max},
Prolog -> {Gray, Map[Line[{{min, #}, {max, #}}] &, #1]},
Frame -> True
] &,
data
],
Plot[potential, {var, min, max}]
] Examples Check that we get the correct numerical eigenvalues for the harmonic oscillator potential $U(x) = \frac{1}{2}x^2$ in dimensionless units: spectrum[10][1/2 x^2, x] {{0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5},
{ψe[<<15>>], ψe[<<15>>], ψe[<<15>>], ψe[<<15>>],
ψe[<<15>>], ψe[<<15>>], ψe[<<15>>], ψe[<<15>>],
ψe[<<15>>], ψe[<<15>>]}} The first list contains the eigenvalues, the second list has the eigenfunctions in shortened form, ready to be plotted. Note from the short forms that that the number of coefficients used in ψe is 15 here, even though I specified that I want to find only 10 eigenvalues in spectrum. This is because these 10 eigenvalues will not be accurate to the given tolerance unless the Hamiltonian matrix is diagonalized in a larger Hilbert space of 15 basis functions. Using FixedPoint , the procedure iteratively increased the number of basis function until none of the first 10 eigenvalues changed by more than the given tolerance in the next iteration. Example 2: quartic oscillator Now we'll look at the eigenstates of a quartic potential, shown here: Plot[-3 x^2 + x^4, {x, -2, 2}] This is a double-well potential, and the low-lying eigenstates will be localized except for a small tunneling coupling. The potential energy is still a polynomial in $x$, so the method should also work here. ψ1 = spectrum[5][-10 x^2 + x^4, x] // Last // Last ψe[<<72>>] Plot[Evaluate[ψ1[x]], {x, -5, 5}] If we plot all eigenstates together, the amplitudes are compressed, but you can discern the distinction between even and odd states: With[{v = -10 x^2 + x^4, n = 10},
plotSpectrum[
spectrum[n][v, x], v, {x, -4, 4}]
] As you can see in the quartic-oscillator example, the number of basis states ( 72 ) is larger for more complicated potentials. But for the harmonic oscillator test case, it's no problem to get very high accuracy for highly excited levels: First[spectrum[100][1/2 x^2, x]] {0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5, 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5, 24.5, 25.5, 26.5, 27.5, 28.5, 29.5, 30.5, 31.5, 32.5, 33.5, 34.5, 35.5, 36.5, 37.5, 38.5, 39.5, 40.5, 41.5, 42.5, 43.5, 44.5, 45.5, 46.5, 47.5, 48.5, 49.5, 50.5, 51.5, 52.5, 53.5, 54.5, 55.5, 56.5, 57.5, 58.5, 59.5, 60.5, 61.5, 62.5, 63.5, 64.5, 65.5, 66.5, 67.5, 68.5, 69.5, 70.5, 71.5, 72.5, 73.5, 74.5, 75.5, 76.5, 77.5, 78.5, 79.5, 80.5, 81.5, 82.5, 83.5, 84.5, 85.5, 86.5, 87.5, 88.5, 89.5, 90.5, 91.5, 92.5, 93.5, 94.5, 95.5, 96.5, 97.5, 98.5, 99.5}
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32293",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1364/"
]
}
|
32,338 |
I want to find the numbers $a$, $b$, $c$, $d$ of the function $y = \dfrac{a x + b}{c x + d}$ so that the triangle $ABC$ with three points $A$, $B$, $C$ have integer coordinates and lies on the graph of the given function, then the centroid of the triangle $ABC$ (have also integer coordinates) is also lies on the graph. I tried Clear[f, m, n, p];
f[x_] := (a x + b)/(c x + d);
m = {h, k};
n = {e, f};
p = {(m[[1]] + n[[1]] + x)/3, (f[m[[1]]] + f[n[[1]]] + f[x])/3}
Reduce[{p[[2]] == f[p[[1]]], f[h] == k, f[e] == f,
Sequence @@ Thread[0 < {a, b, c, d, e, f, h, k, x} < 10],
a < b < c < d}, {a, b, c, d, e, f, h, k, x}, Integers] With my code, I get the answer is False . Is there a triangle like this?
|
Edit A new solution (no luck is needed now :P ): g[x_] := (a x + b)/(c x + 1); (*d is a scale factor or zero*)
cent[x1_, x2_, x3_] := 1/3 ({x1, g[x1]} + {x2, g[x2]} + {x3, g[x3]});
fi = First@FindInstance[{
g@First@cent[x1, x2, x3] == Last@cent[x1, x2, x3],
a/b != c != 0, x1 != x2 != x3,
Element[{x1, x2, x3, g[x1], g[x2], g[x3],Sequence @@ cent[x1, x2, x3]}, Integers]},
{x1, x2, x3, a, b, c}, Reals];
Grid@{
{"p1", {x1, g[x1]}},
{"p2", {x2, g[x2]}},
{"p3", {x3, g[x3]}},
{"Centroid", cent[x1, x2, x3]}} /. fi \begin{array}{cc}
\text{p1} & \{6,-6585\} \\
\text{p2} & \{0,-85\} \\
\text{p3} & \{9,1540\} \\
\text{Centroid} & \{5,-1710\} \\
\end{array} x = {{x1, g[x1]}, {x2, g[x2]}, {x3, g[x3]}};
IntegerQ /@ (Flatten@Join[x, {cent[x1, x2, x3]}] /. fi) {True, True, True, True, True, True, True, True} Grid@{{"a", a}, {"b", b}, {"c", c}} /. fi // TeXForm \begin{array}{cc}
\text{a} & -59 \\
\text{b} & -85 \\
\text{c} & -\frac{7}{45} \\
\end{array}
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32338",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2241/"
]
}
|
32,378 |
I'm visualizing some hydrogen like atomic orbitals. For looking at plane slices of the probability density, the DensityPlot function works well, and with something like: Manipulate[
DensityPlot[ psi1XYsq[u, v, z], {u, -w, w}, {v, -w, w} ,
Mesh -> False, Frame -> False, PlotPoints -> 45,
ColorFunctionScaling -> True, ColorFunction -> "SunsetColors"]
, {{w, 10}, 1, 20}
, {z, 1, 20, 1}
] I can get a nice plot I was hoping that there was something like a DensityPlot3D so that I could visualize these in 3D, but I don't see such a function. I was wondering how DensityPlot be simulated using other plot functions, so that the same idea could be applied to a 3D plot to construct a DensityPlot3D like function?
|
In the version 10.2, there is a builtin DensityPlot3D function, which can be used to visualize orbitals. a0=1;
ψ[{n_, l_, m_}, {r_, θ_, ϕ_}] :=With[{ρ = 2 r/(n a0)},
Sqrt[(2/(n a0))^3 (n - l - 1)!/(2 n (n + l)!)] Exp[-ρ/2] ρ^
l LaguerreL[n - l - 1, 2 l + 1, ρ] SphericalHarmonicY[l,
m, θ, ϕ]]
DensityPlot3D[(Abs@ψ[{3, 2, 0}, {Sqrt[x^2 + y^2 + z^2],
ArcTan[z, Sqrt[x^2 + y^2]], ArcTan[x, y]}])^2, {x, -10 a0,
10 a0}, {y, -10 a0, 10 a0}, {z, -15 a0, 15 a0},
PlotLegends -> Automatic] Or use ListDensityPlot3D : data = Block[
{nψ =
CompileWaveFunction[ψ[3, 1, 0, r, ϑ, φ]], data, vol},
Table[Abs[nψ[x, y, z]]^2, {z, -20, 20, 0.25}, {y, -20, 20, 0.25}, {x, -20, 20, 0.25}]];
ListDensityPlot3D[data] The function definition of the wave function is the same as in the other answer in this question.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32378",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10/"
]
}
|
32,444 |
I am fairly new to Mathematica , and I cannot figure out how to plot an epicycloid . I have plotted some neat looking things in my attempts, but I still can't make one. I am not looking to make an animation; I just want the plot of an epicycloid. Would I use PolarPlot or ParametricPlot ? How do I get a static picture of an epicycloid?
|
I recreated the animation on Wikipedia : Here is the Manipulate version: R = 3; r = 1;
fx[θ_, a_: 1] := (R + r) Cos[θ] - a r Cos[(R + r) θ/r];
fy[θ_, a_: 1] := (R + r) Sin[θ] - a r Sin[(R + r) θ/r];
gridlines = Table[{x, GrayLevel[0.9]}, {x, -6, 6, 0.5}];
plot[max_] := ParametricPlot[
{fx[θ], fy[θ]}, {θ, 0, max},
PlotStyle -> {Red, Thick},
Epilog -> {
Thick,
Blue, Circle[{0, 0}, R],
Black, Circle[{fx[max, 0], fy[max, 0]}, r],
Red, PointSize[Large], Point[{fx[max], fy[max]}],
Black, Line[{{fx[max, 0], fy[max, 0]}, {fx[max], fy[max]}}]
},
GridLines -> {gridlines, gridlines},
PlotRange -> {-6, 6}
]
Manipulate[plot[max], {max, 0.01, 2 Pi}]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32444",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9549/"
]
}
|
32,455 |
I'm trying to figure out how to use FindFit with a multivariable differential equation model and data. I've successfully made it work for the one-variable version of the model by following the example on the Help page: DNA = 10;
model[ a_?NumberQ, b_?NumberQ, c_?NumberQ, d_?NumberQ, f_?NumberQ,
g_?NumberQ, Km1_?NumberQ, Km2_?NumberQ, Km3_?NumberQ, NTP0_?NumberQ] :=
(model[a, b, c, d, f, g, Km1, Km2, Km3, NTP0] =
First[MG /. NDSolve[{ MG'[t] == a*DNA*NTP[t]/(Km1 + NTP[t]) - b MG[t],
NTP'[t] == -f*a*DNA*NTP[t]/(Km1 + NTP[t]) -
d MG[t] NTP[t]/(Km2 + NTP[t]) - c NTP[t]/(Km3 + NTP[t]),
GFP'[t] == g*d MG[t] NTP[t]/(Km2 + NTP[t]),
NTP[0] == NTP0, MG[0] == 0, GFP[0] == 0},
{MG, NTP, GFP}, {t, 0, 800}, Method -> StiffnessSwitching]]);
fit = FindFit[ data, {model[a, b, c, d, f, g, Km1, Km2, Km3, NTP0][t],
a > 0, b > 0, c > 0, d > 0, f > 0, g > 0,
Km1 > 1000, Km2 > 1000, Km3 > 1000, NTP0 > 100000},
{{a, 6.8}, {b, 0.012}, {c, 247}, {d, 1.54}, {f, 19.6}, {g, 22.2},
{Km1, 352200}, {Km2, 127882}, {Km3, 5134.5}, {NTP0, 611628}}, t] where the data looks like: data = {{1.65, 111}, {4.65, 141}, {7.65, 130}, {10.65, 247}, {13.65, 301},
{16.65, 395}, {19.65, 444}, {22.65, 652}, ...}; But now I'd like to do it with DNA being an additional variable included in the data like: newdata = {{1.65, 10, 111}, {4.65, 10, 141}, {7.65, 10, 130}, ..., {1.65, 5, -4},
{4.65, 5, 118}, {7.65, 5, 86}, {10.65, 5, 85}, {13.65, 5, 110}, ...}; so that I could fit multiple curves with different values of DNA simultaneously. I imagine that this is something that's possible, but I'm not sure on the syntax. Anyone have any thoughts on this? ------ EDIT -------- so now I've tried to follow the example that bobthechemist gave on the linked page, but I think I'm getting hung up on the syntax: model[ c_?NumberQ, d_?NumberQ, f_?NumberQ, Km1_?NumberQ, Km2_?NumberQ, Km3_?NumberQ,
Km4_?NumberQ ][ DNA_?NumberQ, t_?NumberQ] :=
(model[c,d,f, Km1,Km2,Km3,Km4][t,DNA] = First[MG/.ParametricNDSolve[{
MG'[t,DNA]==a*DNA*NTP[t,DNA]^n/(Km1^n+NTP[t,DNA]^n)b(Km4^n/(Km4^n+NTP[t,DNA]^n))MG[t,DNA],
NTP'[t,DNA]==-a*f*DNA*NTP[t,DNA]^n/(Km1^n+NTP[t,DNA]^n)-d*MG[t,DNA]NTP[t,DNA]^n/(Km2^n+NTP[t,DNA]^n)-c NTP[t,DNA]^n/(Km3^n+NTP[t,DNA]^n),
NTP[0]==NTP0,MG[0]==0}/.{n->1,b->0.012,a->3.5,NTP0->1500000},{MG,NTP},{t,0,800},{DNA},Method->StiffnessSwitching]]);
fit=FindFit[newdata10,{model[c,d,f, Km1,Km2,Km3,Km4][t,DNA],c>0,0<d,0<f,Km1>100000,Km2>100000,Km3>100000,Km4>100000},{{c,91.0400},{d,8.4986},{f,0.000018697},{Km1,1000100},{Km2,5005020},{Km3,5000150},{Km4,7000000}},{t,DNA},Method->"NMinimize"] gives a whole bunch of errors. perhaps this kind of problem is a bit beyond someone with my limited grasp of Mathematica syntax ------ EDIT 2 -------- a more complete set of data: data = {{2.65,5,86}, {5.65,5,85}, {8.65,5,110}, {11.65,5,153}, {14.65,5,187}, {17.65,5,293}, {20.65,5,321}, {23.65,5,320}, {26.65,5,402}, {29.65,5,355}, {32.65,5,593}, {35.65,5,589}, {38.65,5,653}, {41.65,5,687}, {44.65,5,752}, {47.65,5,858}, {50.65,5,882}, {53.65,5,933}, {56.65,5,1033}, {59.65,5,1043}, {62.65,5,1144}, {65.65,5,1178}, {68.65,5,1239}, {71.65,5,1264}, {74.65,5,1317}, {77.65,5,1452}, {80.65,5,1449}, {83.65,5,1465}, {86.65,5,1480}, {89.65,5,1500}, {92.65,5,1529}, {95.65,5,1531}, {98.65,5,1676}, {101.65,5,1626}, {104.65,5,1632}, {107.65,5,1699}, {110.65,5,1560}, {113.65,5,1651}, {116.65,5,1756}, {119.65,5,1767}, {122.65,5,1715}, {125.65,5,1716}, {128.65,5,1715}, {131.65,5,1732}, {134.65,5,1705}, {137.65,5,1740}, {140.65,5,1759}, {143.65,5,1698}, {146.65,5,1653}, {149.65,5,1628}, {152.65,5,1677}, {155.65,5,1711}, {158.65,5,1608}, {161.65,5,1670}, {164.65,5,1481}, {167.65,5,1563}, {170.65,5,1562}, {173.65,5,1588}, {176.65,5,1540}, {179.65,5,1480}, {182.65,5,1462}, {185.65,5,1424}, {188.65,5,1446}, {191.65,5,1412}, {194.65,5,1380}, {197.65,5,1341}, {200.65,5,1338}, {203.65,5,1263}, {206.65,5,1244}, {209.65,5,1237}, {212.65,5,1164}, {215.65,5,1050}, {218.65,5,1109}, {221.65,5,1041}, {224.65,5,1071}, {227.65,5,908}, {230.65,5,940}, {233.65,5,1013}, {236.65,5,913}, {239.65,5,976}, {242.65,5,886}, {245.65,5,847}, {248.65,5,819}, {251.65,5,784}, {254.65,5,818}, {257.65,5,815}, {260.65,5,807}, {263.65,5,704}, {266.65,5,705}, {269.65,5,816}, {272.65,5,758}, {275.65,5,757}, {278.65,5,633}, {281.65,5,708}, {284.65,5,675}, {287.65,5,632}, {290.65,5,617}, {293.65,5,621}, {296.65,5,594}, {299.65,5,558}, {2.65,10,130}, {5.65,10,247}, {8.65,10,301}, {11.65,10,395}, {14.65,10,444}, {17.65,10,652}, {20.65,10,701}, {23.65,10,840}, {26.65,10,922}, {29.65,10,1074}, {32.65,10,1154}, {35.65,10,1209}, {38.65,10,1326}, {41.65,10,1470}, {44.65,10,1628}, {47.65,10,1600}, {50.65,10,1679}, {53.65,10,1759}, {56.65,10,1856}, {59.65,10,1887}, {62.65,10,2057}, {65.65,10,2078}, {68.65,10,2182}, {71.65,10,2128}, {74.65,10,2034}, {77.65,10,2257}, {80.65,10,2337}, {83.65,10,2362}, {86.65,10,2330}, {89.65,10,2423}, {92.65,10,2471}, {95.65,10,2440}, {98.65,10,2388}, {101.65,10,2544}, {104.65,10,2436}, {107.65,10,2538}, {110.65,10,2402}, {113.65,10,2406}, {116.65,10,2423}, {119.65,10,2365}, {122.65,10,2345}, {125.65,10,2391}, {128.65,10,2412}, {131.65,10,2375}, {134.65,10,2309}, {137.65,10,2321}, {140.65,10,2389}, {143.65,10,2212}, {146.65,10,2211}, {149.65,10,2276}, {152.65,10,2188}, {155.65,10,2112}, {158.65,10,2223}, {161.65,10,1980}, {164.65,10,2046}, {167.65,10,2045}, {170.65,10,2022}, {173.65,10,1933}, {176.65,10,1901}, {179.65,10,1925}, {182.65,10,1829}, {185.65,10,1873}, {188.65,10,1840}, {191.65,10,1855}, {194.65,10,1752}, {197.65,10,1682}, {200.65,10,1639}, {203.65,10,1752}, {206.65,10,1784}, {209.65,10,1661}, {212.65,10,1608}, {215.65,10,1563}, {218.65,10,1462}, {221.65,10,1563}, {224.65,10,1543}, {227.65,10,1448}, {230.65,10,1376}, {233.65,10,1384}, {236.65,10,1383}, {239.65,10,1340}, {242.65,10,1263}, {245.65,10,1362}, {248.65,10,1201}, {251.65,10,1206}, {254.65,10,1220}, {257.65,10,1185}, {260.65,10,1164}, {263.65,10,1133}, {266.65,10,1154}, {269.65,10,1115}, {272.65,10,1122}, {275.65,10,1028}, {278.65,10,1049}, {281.65,10,1042}, {284.65,10,960}, {287.65,10,1011}, {290.65,10,940}, {293.65,10,927}, {296.65,10,877}, {299.65,10,888}}; in each triplet of numbers, the first is the time, second is the DNA parameter value, and the third is the value of the function.
|
I recreated the animation on Wikipedia : Here is the Manipulate version: R = 3; r = 1;
fx[θ_, a_: 1] := (R + r) Cos[θ] - a r Cos[(R + r) θ/r];
fy[θ_, a_: 1] := (R + r) Sin[θ] - a r Sin[(R + r) θ/r];
gridlines = Table[{x, GrayLevel[0.9]}, {x, -6, 6, 0.5}];
plot[max_] := ParametricPlot[
{fx[θ], fy[θ]}, {θ, 0, max},
PlotStyle -> {Red, Thick},
Epilog -> {
Thick,
Blue, Circle[{0, 0}, R],
Black, Circle[{fx[max, 0], fy[max, 0]}, r],
Red, PointSize[Large], Point[{fx[max], fy[max]}],
Black, Line[{{fx[max, 0], fy[max, 0]}, {fx[max], fy[max]}}]
},
GridLines -> {gridlines, gridlines},
PlotRange -> {-6, 6}
]
Manipulate[plot[max], {max, 0.01, 2 Pi}]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32455",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9552/"
]
}
|
32,501 |
I try to obtain random elements from a set given by multiple inequalities. This is of general interest to me, but let me present one example here: I have multiple inequalities specifying half spaces in 2D given by: Eta[a_] := {Cos[a], Sin[a]}
NI[a_] := {Cos[a], Sin[a]}
Table[Dot[{Phi1, Phi2}, Eta[b]]] <= Norm[NI[Pi] - Eta[b]]^2 + 2,
{b, 0, 2 Pi, 2 Pi/10}] The set I am interested in is the intersection of all these inequalities (half spaces). Here is a RegionPlot of the set: RegionPlot[And @@ Table[Dot[{Phi1, Phi2}, Eta[b]]] <= Norm[NI[Pi] - Eta[b]]^2 + 2,
{b, 0, 2 Pi, 2 Pi/10}], {Phi1, -7, 7}, {Phi2, -7, 7}] Now I want to pick random vectors (elements) from this set. My current approach is to define an indicator function for the set like this: set[x1_,x2_] = And @@ Table[Dot[{Phi1, Phi2}, Eta[b]]] <=
Norm[NI[Pi] - Eta[b]]^2 + 2,
{b, 0, 2 Pi, 2 Pi/10}] /. {Phi1 -> x1, Phi2 -> x2} Then use a random number generator for x1 and x2 with appropriate bounds, that I get from inspecting the RegionPlot of the set to obtain a function that gives me n "random" elements from my set: randomVector[n_] := Module[{list = {}, vector, i = 0},
While[i < n,
vector = {RandomReal[{-3, 6}], RandomReal[{-5, 5}]};
If[set[Sequence @@ vector], i++; AppendTo[list, vector];];
];
Return[list];] Do you know of a more elegant way to do this?
|
Lets call your plot res . res = RegionPlot[And @@ Table[
Dot[{Phi1, Phi2}, Eta[b]] <= Norm[NI[Pi] - Eta[b]]^2 + 2, {b, 0,
2 Pi, 2 Pi/10}], {Phi1, -7, 7}, {Phi2, -7, 7}]; Lets extract the mesh Mathematica is generating by default. Use more PlotPoints to get more triangular mesh of your 2D region. pts = res[[1, 1]]; (* Vertices *)
{triangles, qd} = Cases[res[[1]], Polygon[{a___}] -> {a}, Infinity]; (* Triangle and Quads*)
quadTotri = Flatten[{Drop[#, {2}], Take[#, 3]} & /@ qd, 1];(* Quad to Triangle*)
Graphics[{FaceForm[], EdgeForm[Red],GraphicsComplex[pts, Polygon@triangles],
FaceForm[],EdgeForm[{Blue, Dashed}], GraphicsComplex[pts, Polygon@quadTotri]}] Now create a distribution based on the area of those triangles. allTrig = triangles~Join~quadTotri;
vetices = (Extract[pts, Transpose@{#}] & /@ allTrig);
area = .5 Det@((Append[#, 1]) & /@ #) &; (* Calculate area of triangle *)
dat = area /@ (Extract[pts, Transpose@{#}] & /@ (allTrig));
d = EmpiricalDistribution[dat -> Range[Length@allTrig]]; Use random barycentric coordinates to choose the random points from those triangles. Randpts = (Dot[#/Total[#] &@RandomReal[1, 3], #] & /@
Transpose@vetices[[#]]) & /@ RandomVariate[d, 1000];
Show[res, Graphics[{Red, PointSize[Small], Point /@ Randpts}]] Tuning: Using suggestions from @ybeltukov the above can be tied in a function. It takes as argument the RegionPlot graphics output of your region and the number $n$ of random points you want to pick/sample from the region. Clear[RegionRandom];
RegionRandom[plot_Graphics, n_] := Block[{pts, triangles, qd, quadTotri,
allTrig, vetices, areas,
empdist, u0, u1, u2, CustomDistribution, rp},
pts = plot[[1, 1]];
{triangles, qd} =Cases[plot[[1]], Polygon[{a___}] -> {a}, Infinity];
allTrig =
triangles~Join~Flatten[{Drop[#, {2}], Take[#, 3]} & /@ qd, 1];
vetices = (Extract[pts, Transpose@{#}] & /@ allTrig);
areas =
0.5 Abs[#1[[All, 2]] #2[[All, 1]] - #1[[All, 1]] #2[[All,
2]]] &[#[[All, 2]] - #[[All, 1]], #[[All, 3]] - #[[All,
1]]] &@vetices;
empdist = EmpiricalDistribution[areas -> Range@Length@vetices];
u0 = vetices[[All, 1]];
u1 = vetices[[All, 2]] - u0;
u2 = vetices[[All, 3]] - u0;
CustomDistribution /:
Random`DistributionVector[CustomDistribution[], p_Integer,
prec_?Positive] :=
Module[{s =
RandomVariate[DirichletDistribution[{1, 1, 1}], p,
WorkingPrecision -> prec],
m = RandomVariate[empdist, p, WorkingPrecision -> prec]},
u0[[m]] + s[[All, 1]] u1[[m]] + s[[All, 2]] u2[[m]]
];
rp = RandomVariate[CustomDistribution[], n]
]; Lets test it with above RegionPlot named res for $40000$ random points. pt = RegionRandom[res, 40000];
Show[res, Graphics[{Red, PointSize[Tiny], Point /@ pt}]] Also some fun with nontrivial 2D regions. Result is not too bad! You can use this answer to create nicer 2D mesh of your region than the default one. I may update that later! Comparison: Histogram: First lets see the histogram for $20000000$ sample! Histogram3D[RegionRandom[res, 20000000], 25] Entropy of generated data: We know entropy is an information theoretic metric to measure the intrinsic randomness of sample. We use Entropy function to test which algorithm provides more randomness. Mahalanobis distance: We also compare the Mahalanobis distance pdf of both the sample generators as it gives a visual presentation of their mutual disagreement. n=50000; (* reduce n to as the following is very memory intensive ~ I had 64 Gb RAM *)
{TrigData, MetData} = {RegionRandom[res, n],
RandomVariate[Metropolis[pdf, {2, 0}], n]};
MahalanobisDistance[data_] :=
Block[{m = Mean[data], cov = Inverse[Covariance[data]], temp},
temp = (#1 - m &) /@ data; Diagonal[temp.cov.Transpose[temp]]]
dist = SmoothKernelDistribution[MahalanobisDistance[#]] & /@ {TrigData, MetData}; Timing: The Metropolis algorithm performs faster after compilation by @ybeltukov pt1 = RandomVariate[Metropolis[pdf, {2, 0}],20000000]; // AbsoluteTiming {9.653125, Null} pt = RegionRandom[res, 20000000]; // AbsoluteTiming {14.207429, Null}
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32501",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5033/"
]
}
|
32,612 |
Q1 : I have a page of a printed text file, but it was cut by a paper shredder (from top to bottom). You can download all the paper fragments here . Here are some of them. How can I reconstruct it? Q2 : This time, the situation is even worse - the page was cut by a shredder twice (from top to bottom and from left to right)! ( Get the fragments here ). My code for Q1 : filenames = FileNames["*.bmp", "C:\\Users\\Liao\\Desktop\\B\\file1"];
pics = Import /@ filenames;
binarypic = Binarize[#, 0.9] & /@ pics;
binarydata = ImageData /@ binarypic;
leftandrightdata =
MapIndexed[{#2[[1]], #1[[All, 1]], #1[[All, -1]]} &, binarydata];
result = {};
firstPic = Select[leftandrightdata, ! MemberQ[#[[2]], 0] &][[1, 1]];
start = leftandrightdata[[firstPic]];
DeleteCases[leftandrightdata, start] //.
x_ /; Length[x] > 0 :> (sort =
SortBy[x, HammingDistance[#[[2]], start[[3]]] &];
AppendTo[result, start = sort[[1]]]; Rest[sort]);
Extract[pics,
Prepend[List /@ result[[All, 1]], {firstPic}]] // ImageAssemble This code maybe dizzy for you, but it doesn't matter. The core idea is simple and straightforward, which use HammingDistance to determine whether two images can be combined together. But for Q2 , I can't really find a good way to solve it.
|
Q1 pics = Binarize /@ (Import /@ FileNames["*.bmp"]);
(*extracting edges*)
left = ImageData[#][[All, 1]] & /@ pics;
right = ImageData[#][[All, -1]] & /@ pics; Let's find the left edge, here I'm assuming that it is all white. So if pics // First // ImageDimensions {72, 1980} and an image is binarized then the left edge is: Total /@ left // Position[#, 1980, 1] & {{4}} Instead of HammingDistance I'm calculating Norm : cons = {4};
Do[
With[{dists = Norm[right[[cons[[-1]]]] - #] & /@ left},
AppendTo[cons, Position[dists, Min@dists, 1][[1, 1]] ]
]
, {Length@pics - 1}]
ImageAssemble@pics[[cons]]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32612",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5110/"
]
}
|
32,689 |
How to plot periodic function's graphic? For example, $f(t) = t$ when $-5<t<5$ and $f(t+10) = f(t)$. f[t] := If[-5 <= t <= 5, t, f[t + 10] = f[t]];
Plot[f[t], {t, -20, 20}]
|
What about this? This defines a rather general function myperiodic that translate a normal function to periodic form, the second parameter {val, min, max} specify a periodic interval of your desired periodic function: myperiodic[func_, {val_Symbol, min_?NumericQ, max_?NumericQ}] :=
func /. (val :> Mod[val - min, max - min] + min) Then you can use it to plot things: Plot[myperiodic[t, {t, -5, 5}] // Evaluate, {t, -40, 40}] Plot[myperiodic[t^2, {t, -3, 5}] // Evaluate, {t, -40, 40}] Extensions We can extend this function in a couple of possibly useful ways. It may be noted that if t has a global value the plots above will fail, because Evaluate breaks the scoping of Plot . This could be remedied by using the Evaluated option but it would be nice not to need either. We can achieve that by holding arguments unevaluated using HoldAll and then holding at least the Symbol and expression unevaluated while making the substitution. These methods come to mind: Adding Unevaluated and HoldPattern to the existing replacement leveraging the attributes of Pattern and RuleDelayed in an inverted rule form (injector pattern) Using Function which holds parameter name and body An undocumented syntax for With ( := ) that does not evaluate substitution expressions In code: SetAttributes[{periodic1, periodic2, periodic3, periodic4}, HoldAll]
periodic1[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] :=
Unevaluated[expr] /. HoldPattern[s] :> Mod[s, max - min, min]
Quiet[
periodic2[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] :=
Mod[s, max - min, min] /. s_ :> expr
]
periodic3[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] :=
Function[s, expr][Mod[s, max - min, min]]
periodic4[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] :=
With[{s := Mod[s, max - min, min]}, expr] Testing indicates that the last method is the fastest: First @ AbsoluteTiming @ Do[#[7 + t^2, {t, -5, 5}], {t, -40, 40, 0.001}] & /@
{periodic1, periodic2, periodic3, periodic4} {0.35492, 0.382667, 0.237522, 0.235105} Demonstration of use: Plot[periodic4[7 + t^2, {t, -5, 5}], {t, -40, 40}, Frame -> True] The next extension that can be valuable it to have periodic return a function rather than a bare expression. While the functions above evaluate correctly internally in the presence of a global assignment to the declared Symbol the result evaluates with that global value and therefore cannot be reused. Returning a function allows us to use it more generally such as mapping over a list of values, which can have advantage as I will show. Proposal SetAttributes[periodic, HoldAll]
periodic[expr_, {s_Symbol, min_?NumericQ, max_?NumericQ}] :=
Join[s &, With[{s := Mod[s, max - min, min]}, expr &]] (Note that Join works on any head. Function acts to hold the parts of the final Function before it is assembled.) Now: periodic[7 + t^2, {t, -5, 5}] Function[t, 7 + Mod[t, 5 - -5, -5]^2] Plot[periodic[7 + t^2, {t, -5, 5}][x], {x, -40, 40}, Frame -> True] (Note that x was used above for clarity but using t would not conflict.) If the somewhat awkward from of Function returned is a concern know that it will be optimized by Compile , either manually or automatically: Compile @@ periodic[7 + t^2, {t, -5, 5}] CompiledFunction[{t}, 7 + (Mod[t + 5, 10] - 5)^2, -CompiledCode-] The function-generating form does not perform quite as well (as e.g. periodic4 ) when used naively: Table[periodic[7 + t^2, {t, -5, 5}][t], {t, -40, 40, 0.001}] // AbsoluteTiming // First 0.3600206 However it allows for superior performance if applied optimally, using Map , which auto-compiles: periodic[7 + t^2, {t, -5, 5}] /@ Range[-40, 40, 0.001] // AbsoluteTiming // First 0.0130007 As a final touch we can give our function proper syntax highlighting: SyntaxInformation[periodic] =
{"LocalVariables" -> {"Table", {2}}, "ArgumentsPattern" -> {_, {_, _, _}}}; – Mr.Wizard
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32689",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9627/"
]
}
|
32,716 |
One difficulty I'm encountering in studying the structure of Graphics objects is that I have not yet found a way to print or display such structures that are sufficiently general. The FullForm of Graphics objects can be huge and extremely difficult to take in visually. I have tried to deal with this using Shallow , but with only limited success, because I find that "the interesting bits" in a Graphics not always occur at the same depth. It's a chicken-and-egg problem: to write a function that displays such structure in a useful way, I need to understand what such structure could be. But gaining this understanding is precisely what I'm trying to do here! In case it matters, I'm primarily interested in examining the structure of Graphics objects generated, directly or indirectly, by plotting commands such as Plot , ListPlot , etc.
|
Finally, the following code gives you an interactive tree. You might want to enlarge the area of the tree if the nodes are too small. structureOfGraph[gr_] := Module[{xx = gr /. Rule[a_, _] :> a /.
x_ /; And @@ NumericQ /@ x :> x[[0]] /. {List ..} :>
ListOfLists}, Manipulate[TreeForm[xx, n], {n, 1, Depth[xx] - 1, 1}]];
structureOfGraph[Show[Plot[{Cos[x], Sin[x]}, {x, 0, 4 Pi}], Graphics[{Circle[]}]]] Second iteration This second attempt makes an even shorter tree by getting rid of the terminal List : TreeForm[Graphics[{Blue, {EdgeForm[{Red, Thick}], Disk[]},
Disk[{1, 0}]}] /. x_ /; And @@ NumericQ /@ x :> x[[0]] /. x_[List] :> x] First iteration I will send this as an answer because I cannot add comments with graphics to this previous answer . TreeForm[Graphics[{Blue, {EdgeForm[{Red, Thick}], Disk[]},
Disk[{1, 0}]}] /. x_ /; And @@ NumericQ /@ x :> x[[0]]] produces
|
{
"source": [
"https://mathematica.stackexchange.com/questions/32716",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2464/"
]
}
|
33,574 |
I'm trying to apply a Fourier transform of a one dimensional list of a time history of some quantity using the Fourier function. I'm interested in the frequency spectrum, but the problem is that the Fourier function uses the fast Fourier transform algorithm which places the zero frequency at the beginning, complicating my analysis of the results. So how can I shift the zero frequency to the center? I tried to search for the solution and found two methods, which seem to give contradicting answers. Method 1 (from course notes available here ). It simply rotates the list before and after the Fourier transform: DFT1[ls_?(EvenQ@Length[#] &), dt_] := Module[{N0, fft},
N0 = Length[ls];
fft = RotateRight[
dt*Fourier[RotateLeft[ls, N0/2 - 1], FourierParameters -> {1, 1}],
N0/2 - 1];
fft
] Method 2 (from some code of my professor). It rotates the list only after the transform, and adds a phase shift: DFT2[ls_?(EvenQ@Length[#] &), dt_] := Module[{N0, dw, wls, fft},
N0 = Length[ls];
dw = (2 π)/(N0 dt);
wls = dw Range[-(N0/2), N0/2 - 1];
fft = dt*
Reverse[RotateRight[Fourier[ls, FourierParameters -> {1, -1}],
N0/2 - 1]]*Exp[(I π)/dw wls];
fft
] If we use these two methods on an example, we get different answers: dt = 0.05;
els = Table[Sin[ t] Sin[t/40]^2, {t, 0., 40 π, dt}];
ListPlot[els, Joined -> True] Row[ListPlot[{#[DFT1[els, dt]], #[DFT2[els, dt]]}, Joined -> True,
PlotRange -> {{1200, 1300}, All}, ImageSize -> 300] & /@ {Abs, Re,
Im}] Questions: Which of the methods is correct (if neither is correct then what is the right way)? What are the frequencies corresponding to the Fourier transform results? For example, should the frequencies range from $\{-\frac{N0\Delta \omega}{2},\frac{(N0-1)\Delta \omega}{2}\}$ or $\{-\frac{(N0-1)\Delta \omega}{2},\frac{N0\Delta \omega}{2}\}$? $N0$ is the length of the data, $\Delta t$ is the time interval of the data, $\Delta \omega=\frac{2\pi }{N0 \Delta t}$. What difference does it make if N0 is even or odd? Update : This is the result using the method in Bill's answer here to a similar question. The results appear to differ from both of the approaches mentioned above. n = Length[els];
sampInt = dt;
data = els;
ssf = RotateRight[Range[-n/2, n/2 - 1]/(n sampInt), n/2];
fft = dt Fourier[data, FourierParameters -> {1, 1}];
Row[ListPlot[#@
Sort[Transpose[{ssf, fft}], #1[[1]] < #2[[1]] &][[All, 2]],
PlotRange -> {{1200, 1300}, All}, Joined -> True,
ImageSize -> 300] & /@ {Abs, Re, Im}]
|
The Fourier transform is defined as: $$
\begin{align*}
H(f) &= \int_{-\infty}^\infty h(t) \mathrm e^{2\pi \mathrm i f t}\mathrm dt\\
h(t) &= \int_{-\infty}^\infty H(f) \mathrm e^{-2\pi \mathrm i f t}\mathrm df
\end{align*}
$$ where $ h(t) $ is the signal, and $ H(f) $ is its Fourier transform; if $ t $ is measured in seconds, then $ f $ is measured in hertz (Hz). The discrete Fourier transform is defined as: $$
\begin{align*}
H_{f_j} &= \frac{1}{N}\sum_{k}h_{t_k}\mathrm e^{2\pi \mathrm i f_j t_k}\\
h_{t_j} &= \frac{1}{N}\sum_{k}H_{f_k}\mathrm e^{-2\pi \mathrm i f_k t_j}\\
\end{align*}
$$ where the $ t_k $ are the time corresponding to my signal in the time domain $ h_{t_k} $ , $ f_k $ are the corresponding frequency to my signal in the frequency domain, and $ N $ is the number of points of the signal data. For example, if my signal data has $ N $ points, and it was taken at a time interval of $ \Delta t $ , then: The period of this signal is $$ N*\Delta t $$ The frequency interval of the Fourier transform is $$ \Delta f=\frac{1}{N*\Delta t} $$ The time range of the signal is $$ \text{from}~~~0~~~\text{to}~~~(N-1)*\Delta t $$ The frequency range of the Fourier transform is $$ \text{from}~~~0~~~\text{to}~~~(N-1)*\Delta f $$ We can also see from the definition of the discrete Fourier transform that for any frequency, we can shift it with $ \frac{1}{\Delta t} $ and get the same answer since $$ \mathrm e^{2\pi \mathrm i (f_k+1/\Delta t)t_k}=\mathrm e^{2\pi \mathrm i f_k t_k} $$ which means that frequency $ (N-1)\Delta f $ is the same as $ -\Delta f $ . So we can change all the second half of the higher frequencies into the their negative counterpart, so that the frequencies are now symmetric around zero frequency: $$
\begin{array}{cccccccccc}
0 & \Delta f & 2\Delta f & ... & (\frac{N}{2}-1)\Delta f & \frac{N}{2}\Delta f & (\frac{N}{2}+1)\Delta f & ... & (N-1)\Delta f\\
\downarrow & \downarrow &\downarrow && \downarrow & \downarrow & \downarrow & & \downarrow\\
0 & \Delta f & 2\Delta f & ... & (\frac{N}{2}-1)\Delta f &-\frac{N}{2}\Delta f &(-\frac{N}{2}+1)\Delta f & ... &-\Delta f&
\end{array}
$$ If we want to arrange the frequencies from negative to positive, we can simply rotate $ N/2 $ places to the right. Here's one way to go about it, building on this answer and using the OP's function. dt = 0.05;
els = Table[Sin[t] Sin[t/40]^2, {t, 0., 40 π, dt}];
n = Length[els];
ssf = RotateRight[Range[-n/2, n/2 - 1]/(n dt), n/2];
fft = Fourier[els, FourierParameters -> {-1, 1}];
ListPlot[Select[Transpose[{ssf, Abs[fft]}], Abs[#[[1]]] < 0.5 &],
PlotRange -> All, Filling -> Axis] The only difference here is selecting the $x$ -axis values less than 0.5 Hz (needed because otherwise, the data is hard to see). You can eyeball this data to see that it's about right: the curve els has about 20 periods in 2500 samples. This is a normalized frequency of about 0.016, as seen in the graph. Looking at the ssf vector, the exact frequency is 0.159109 , which occurs in location 21 of the ssf vector. Location 21 of the fft vector is the one with the magnitude at about 0.25 , the peak value. Update: For $n$ an odd number, the frequency arrangement is slightly different: $$
\begin{array}{ccccccccc}
0 & \Delta f & 2\Delta f & ... & (\frac{N-1}{2})\Delta f & (\frac{N+1}{2})\Delta f & ... & (N-1)\Delta f\\
\downarrow & \downarrow &\downarrow && \downarrow & \downarrow & & \downarrow\\
0 & \Delta f & 2\Delta f & ... & (\frac{N-1}{2})\Delta f &(-\frac{N-1}{2})\Delta f & ... &-\Delta f&
\end{array}
$$ so for the data with an odd number of points, we only need to change the frequencies to be ssf = RotateRight[Range[-(n-1)/2, (n-1)/2 ]/(n dt), (n+1)/2]; and we will be OK.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/33574",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1364/"
]
}
|
33,652 |
What's the right way to generate a random probability vector $p={p_1,\ldots,p_n} \in {(0,1)}^n$ where $\sum_i p_i=1$, uniformly distributed over the $(n-1)$-dimensional simplex? What I have is Intervals = Table[{0, 1}, {i, n}]
RandomPoint := Block[{a},
a = RandomVariate[UniformDistribution[Intervals]];
a/Total[a]]; But I am unsure that this is correct. In particular, I'm unsure that it's any different from: RandomPoint := Block[{a},
a = Table[Random[], {i, n}];
a/Total[a]]; And the latter clearly will not distribute vectors uniformly. Is the first code the right one?
|
#/Total[#,{2}]&@Log@RandomReal[{0,1},{m,n}] will give you a sample of m points from a uniform distribution over an n-1 -dimensional regular simplex. (An equilateral triangle is a 2-dimensional regular simplex.) Here's what m = 2000, n = 3 should look like, where {x,y} = {p[[2]]-p[[1]], Sqrt@3*p[[3]]} are the barycentric coordinates of the 3-element probability vector p : Here's what you get if you omit the Log@ and normalize Uniform(0,1) variables, which is what both of the OP's examples do:
|
{
"source": [
"https://mathematica.stackexchange.com/questions/33652",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9898/"
]
}
|
33,655 |
How to write beveled fractions like ${}^a/_b$? In contrast to $\frac{a}{b}$ and $a/b$ (see this question).
|
There is the undocumented option Beveled in the FractionBox FractionBox[a, b, Beveled -> True] // DisplayForm
|
{
"source": [
"https://mathematica.stackexchange.com/questions/33655",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/4678/"
]
}
|
34,073 |
How to calculate the integral of $\frac{1}{\sqrt{4 z^2 + 4 z + 3}}$ over the unit circle counterclockwise for each branch of the integrand?
|
The integrand has two singular points: Solve[ 4z^2 + 4z + 3 == 0, z] {{z -> 1/2 (-1 - I Sqrt[2])}, {z -> 1/2 (-1 + I Sqrt[2])}} At infinity it becomes zero: Limit[ 1/Sqrt[ 4 z^2 + 4 z + 2], z -> ComplexInfinity] 0 All these points are the branch points, thus we should define appropriately integration contours in order to avoid possible jumps of the function when moving around a given closed path. To get a general view on the issue we'll discuss two choices of contours (there are possible many other). Mathematica chooses arbitrary branch cuts of the function, it can be easily seen from e.g. ContourPlot or Plot3D of the real and imaginary parts of the integrand, e.g. With[{z1 = 1/2 (-1 - I Sqrt[2]), z2 = 1/2 (-1 + I Sqrt[2])},
GraphicsRow[
Table[ ContourPlot[ g[1/Sqrt[4 (x + I y - z1) (x + I y - z2)]],
{x, -1.5, 1.5}, {y, -1.5, 1.5},
ColorFunction -> "GrayYellowTones",
Epilog -> {Cyan, Thick, Circle[{0, 0}], Red, PointSize[0.02],
Point[{Re @ #, Im @ #}& /@ {z1, z2}]},
Contours -> 11],
{g, {Re, Im}}]]] On the other hand using the Cauchy Integral Theorem we can choose appropriate contours to perform needed calculations. The main problem here is providing a clear graphical presentation of chosen contours. Solution 1 Let's define a function which will be used to draw contours: cp[{x_, y_}, r_, t_, ϕ_, δ_] :=
ConditionalExpression[ {x, y} + r {Cos[t + ϕ], Sin[t + ϕ]}, δ <= t <= 2 Pi - δ] now supplementing the following plot with arrows and symbols Style[Subscript[C, #], 28, Bold, FontFamily -> "Times", Blue] & /@ Range[8] pasted into the graphics with drawing tools ( Ctrl + D ): Module[
{z1 = 1/2 (-1 - I Sqrt[2]), z2 = 1/2 (-1 + I Sqrt[2]), z11, z22, r = 1/10, δ, δ1},
{z11, z22} = {Re @ #, Im @ #}& /@ {z1, z2}; δ = 2 r; δ1 = δ/7;
ParametricPlot[{ cp[{0, 0}, 1, t, {0}, δ1], cp[ z11, r, t, -Pi + Arg[z1], δ],
cp[ z22, r, t, -Pi + Arg[z2], δ]}, {t, 0, 2 Pi},
PlotStyle -> ConstantArray[{Thick, Darker @ Blue}, 3],
AxesStyle -> Arrowheads[0.03],
PlotRange -> {{-1.05, 1.35}, {-1.1, 1.1}},
Epilog -> {Darker @ Blue, Thick, Line @ {
{ cp[z11, r, δ, -Pi + Arg[z1], 0], { Sin[Arg[z1]] δ1, 0},
cp[z22, r, 2 Pi - δ, -Pi + Arg[z2], 0]},
{ cp[z11, r, 2 Pi - δ, -Pi + Arg[z1], 0], {0, Sin[Arg[z1]] δ1},
{1, Sin[Arg[z1]] δ1}},
{ cp[z22, r, δ, -Pi + Arg[z2], 0], {0, - Sin[Arg[z1]] δ1},
{1, - Sin[Arg[z1]] δ1}}},
Darker @ Magenta, Dashing[{0.035, 0.013}], Thickness[0.004],
Line @ { {z11, {0, 0}, {1.25, 0}}, {z22, {0, 0}}},
Red, PointSize[0.015], Point[{z11, z22}]}, ImageSize -> 750]] denoting integrals over contours $\;C, C_1,\dots,C_8\;$ by iC, iC1, iC2, ..., iC8 ,
from the Cauchy theorem we have: iC + iC1 + iC2 + iC3 + iC4 + iC5 + iC6 + iC7 + iC8 == 0 for any r > 0 being the radius of the small circles and δ being the half distance between apprporiate parallel contours. On the graphics δ and r are related, but mathematically we need only evaluating integrals when r -> 0 and δ -> 0 . Let's find limits of the integrals iC3, iC6 when r tends to zero. Parametrizing z first with z == z[t] -> z1 + r E^(I t) and then with z == z[t] -> z2 + r E^(I t) we have: With[{z1 = 1/2 (-1 - I Sqrt[2]), z2 = 1/2 (-1 + I Sqrt[2])},
Limit[{ Integrate[(r I E^(I t))/(2 Sqrt[r E^(I t) (r E^(I t) + z1 - z2)]), {t, 0, 2 Pi},
Assumptions -> r > 0],
Integrate[(r I E^(I t))/(2 Sqrt[r E^(I t) (r E^(I t) + z2 - z1)]), {t, 0, 2 Pi},
Assumptions -> r > 0]}, r -> 0]] { 0, 0} To calculate another integrals we need to observe that after moving around the small contours $C_3$ and $C_6$ the phase changes according to the rule: t -> t + 2Pi , taking e.g. 1/Sqrt[4 z^2 + 4 z + 3] /. z -> 1/2 (-1 - I Sqrt[2]) + r E^(I t) // FullSimplify 1/(2 Sqrt[E^(I t) r (-I Sqrt[2] + E^(I t) r)]) increment of t by 2Pi implies multiplication of the integrand by -1 (when r is small only the first term in Sqrt is affected by increment of t while the second one remains constant approximately, in the limit r -> 0 it is -I Sqrt[2] ). Moreover the both integrals iC2 and iC4 as well as iC5 and iC7 are oriented oppositely, thus iC2 + iC4 == 2 iC2 and iC5 + iC7 == 2 iC7 . However iC1 == - iC8 because the integrand changed the sign two times when we moved around the singularities. We need to parametrize z on $C_2$ and $C_4$ with z == z[t] -> t z1 and with z == z[t] -> t z2 on $C_5$ and $C_7$ respectively.
Concluding all of the above remarks we find that: FullSimplify[
Plus @@ With[{z1 = 1/2 (-1 - I Sqrt[2]), z2 = 1/2 (-1 + I Sqrt[2])},
{ 2 Integrate[ z2/Sqrt[ 4 (t - 1) z2 (t z2 - z1)], {t, 0, 1}],
-2 Integrate[ z1/Sqrt[ 4 (t - 1) z1 (t z1 - z2)], {t, 0, 1}]}]] I Pi thus iC == -I Pi . Solution 2 Module[
{z1 = 1/2 (-1 - I Sqrt[2]), z2 = 1/2 (-1 + I Sqrt[2]), z11, z22, r = 1/10, δ, δ1},
{z11,z22} = {Re @ #, Im @ #}& /@ {z1, z2}; δ = 2 r; δ1 = δ/7;
ParametricPlot[{cp[{0, 0}, 1, t, Pi, δ1], cp[z11, r, t, Pi/2, δ],
cp[z22, r, t, -Pi/2, δ]}, {t, 0, 2 Pi},
PlotStyle -> ConstantArray[{Thick, Darker@Blue}, 3],
AxesStyle -> Arrowheads[0.03], PlotRange -> {{-1.25, 1.1}, {-1.1, 1.1}},
Epilog -> {Darker @ Blue, Thick, Line @ {
{ cp[z11, r, Pi/2 -δ, 0, 0], cp[z22, r, δ, -Pi/2, 0]},
{ cp[z11, r, Pi/2 + δ, 0, 0], {-1/2 - Sin[δ1], -δ1}, {-1, -δ1}},
{ cp[z22, r, Pi/2 - δ, Pi, 0], {-1/2 - Sin[δ1], δ1}, {-1, δ1}}},
Darker @ Magenta, Dashing[{0.035, 0.013}], Thickness[0.004],
Line @ {{z11, z22}, {{-1.2, 0}, {-1/2, 0}}}, Red, PointSize[0.015],
Point[{z11, z22}]}, ImageSize -> 750]] Now iC1 + iC7 == 0 and iC2 + iC6 == iC4 . iC3 and iC5 tends to zero as r -> 0 , thus we have: With[{z1 = 1/2 (-1 - I Sqrt[2]), z2 = 1/2 (-1 + I Sqrt[2])},
Integrate[( 2 I)/Sqrt[3 + 4 (I t + z1) + 4 (I t + z1)^2], {t, 0, Sqrt[2]}]] I Pi therefore iC == -I Pi . We provided the both solutions in the case when the contours are connected, but it is not necessary, it is needed only that they are connected with ComplexInfinity .
|
{
"source": [
"https://mathematica.stackexchange.com/questions/34073",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7152/"
]
}
|
34,242 |
I'm trying to get an algorithm that generates a picture like this So far I've tried a little something with the help of the knowledge center, getting a graphics grid of squares already. But what now? I'm completely in the dark on how to trim it in the circle-shape I want. (If there are better solutions out there, please forget what I have started with. My only goal is to get the end result where I can make a pattern like this with variable size in terms of diameter in squares, size of the squares themselves and spacing in between.) size = 10;
scalesize = 1;
table1 = Table[Graphics[Rectangle[]], {size}, {size}];
GraphicsGrid[table1, Frame -> None, Spacings -> Scaled[scalesize]]
|
The only thing you need for the underlying data is DiskMatrix . The rest of the visualization can be chosen freely: ArrayPlot[ArrayPad[DiskMatrix[7], 1], ColorFunction -> GrayLevel,
Mesh -> All, MeshStyle -> Directive[Thickness[.02], Black]]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/34242",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10077/"
]
}
|
34,251 |
I am constructing a diagram that consists of a sine curve and its tangent line at a given argument. However, I want to show the coordinates of the point of tangency and the equation of the tangent line dynamically. My work so far: f[x_] := Sin@x;
l[x_, a_] := f[a] + f'[a] (x - a);
Manipulate[
Show[
Plot[Sin@x, {x, 0, 2 \[Pi]},
PlotRange -> {-2, 2}, AxesStyle -> Arrowheads[0.03],
AxesLabel -> {"x", "Sin[x]"}, AspectRatio -> Automatic,
PlotLabel -> f[a] <> "+" <> f'[a] ("x-" <> a)],
Plot[l[x, a], {x, a - 2, a + 2}, PlotStyle -> Pink],
Graphics[{PointSize[Medium], Red, Point[{a, Sin@a}]}]],
{a, 0, 2 \[Pi]}] Unfortunately, what I've done doesn't work. So my question is: how do I get the information I need to make it work.
|
The only thing you need for the underlying data is DiskMatrix . The rest of the visualization can be chosen freely: ArrayPlot[ArrayPad[DiskMatrix[7], 1], ColorFunction -> GrayLevel,
Mesh -> All, MeshStyle -> Directive[Thickness[.02], Black]]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/34251",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9627/"
]
}
|
34,861 |
One of my Mathematica interests is in problems related to the formatting of output. Getting nice formatting from Mathematica is often frustrating, but occasionally Mathematica will delight me by making a formatting task, which I anticipated would be difficult, easy. I want to share one such recent experience by posing it as a question. Can you create a 10-row, 5-column table in Mathematica presenting the results from running a dice game simulation in which a pair of dice is rolled 50 times? The table should look like this: Your solution may show a different sequence of dice rolls. Note that rolls of seven are highlighted in red. That feature must be reproduced. I post this question, not because it is difficult (it isn't), but because I had fun with it myself. I will post my answer in 48 hours, providing nobody posts an equivalent answer beforehand.
|
We have unicode support so we can use the following strings: {"⚀", "⚁", "⚂", "⚃", "⚄", "⚅"} : dice = FromCharacterCode /@ Range[9856, 9856 + 5];
Grid[Partition[RandomInteger[{1, 6}, {50, 2}], 5] /. {
i : {__Integer} :> Style[
Row[dice[[i]], Spacer[1]],
{Large, Total[i] /. {7 -> Red, _ -> Black}}]}
, Frame -> All]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/34861",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/3066/"
]
}
|
34,867 |
I am trying to plot this graph showing the electric field lines and lines of equipotential based off the electrode configuration(in black) of two parallel lines. This is what I've been using for other electrode configurations: gradientFieldPlot[(y^2 + (x - 7/2)^2)^(-1/2) - (y^2 + (x + 7/2)^2)^(-1/2), {x, -7, 7},
{y, -5, 5}, PlotPoints -> 50, ColorFunction -> "BlueGreenYellow",
Contours -> 15,ContourStyle -> White, Frame -> True,
FrameLabel -> {"x", "y"}, ClippingStyle -> Automatic, Axes -> True,
StreamStyle -> Orange] and am trying to do it in a similar manner, but I do not know how to express the equations for these two finite parallel lines in the [ ] .
Can any one help? Thanks sooo much!!
|
We have unicode support so we can use the following strings: {"⚀", "⚁", "⚂", "⚃", "⚄", "⚅"} : dice = FromCharacterCode /@ Range[9856, 9856 + 5];
Grid[Partition[RandomInteger[{1, 6}, {50, 2}], 5] /. {
i : {__Integer} :> Style[
Row[dice[[i]], Spacer[1]],
{Large, Total[i] /. {7 -> Red, _ -> Black}}]}
, Frame -> All]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/34867",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10227/"
]
}
|
35,193 |
Here are the data that I want to plot: meandatf1 = Mean /@ datf1
meandatf2 = Mean /@ datf2
{1.48908, 1.49641, 1.49354, 1.50385, 1.49835, 1.49617, 1.50569, \
1.50117, 1.50226, 1.50151, 1.50108, 1.50031, 1.49955, 1.49721, \
1.49898, 1.50266, 1.50177, 1.50227, 1.49886, 1.50002}
{-0.00127783, 0.000556012, 0.0000143709, -0.000602328, -0.000375952, \
-0.00125357, 0.0000228143, 0.000175103, 0.000868018, -0.0003298, \
0.000230178, 0.000222689, -0.0000624273, -0.0000760139, -0.000263302, \
0.0000826082, 0.000206463, 0.0000507921, -0.0000955452, 0.000184107} And here is how I generate my individual plots: genPlot[c_, dat_, ymin_, ymax_, legend_] :=
ListPlot[{
Table[c, {Length[dat]}], dat},
AxesLabel -> {"N", "\[Mu]"}, PlotRange -> {Automatic, {ymin, ymax}},
PlotLegends -> Placed[legend, Above],
Joined -> True, Mesh -> None, InterpolationOrder -> 0,
ImageSize -> 400] (* I tried also without ImageSize, see below *)
plot1 = genPlot[3/2, meandatf1, 1.45, 1.55, "\[ScriptCapitalD]1"]
plot2 = genPlot[0, meandatf2, -0.004, 0.004, "\[ScriptCapitalD]2"] The output of the individual plots is fine: But when I combine the two plots with GraphicsRow[] I get this ugly output: When I don't specify ImageSize in genPlot[] the combined plot is very small (but otherwise looks fine): If I set ImageSize in the GraphicsRow[] (and not in genPlot[] ) the container image is increased instead of the contained cells (which is reasonable, but was a desperate long shot by my side): It must be something trivial that I am missing. Any ideas? EDIT1 : I am using Mathematica 9.0.1 under Mac OSX Mavericks. EDIT2 : Pretty much all of the proposed solutions worked for me. I wish I could accept >1 but, since this is not possible, I'll accept the one from @JasonB for its beauty of simplicity.
|
GraphicsRow , GraphicsGrid , or GraphicsColumn can be useful, when you need the output to be a Graphics object. But it's often easier to just use the corresponding non- Graphics version; I find the resizing and spacing options easier to use. When I do Grid[{{plot1, plot2}}] I get which I think is what you want.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/35193",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9083/"
]
}
|
35,261 |
I want to define a function f with an argument that matches only when an argument Head is NOT of a given value. I know I can define a pattern that matches the Head for an argument: f[a_Integer] := 2 a Now, how do I define a version that matches only when argument a is NOT an Integer? f[a_NotAnInteger] := <something else>
|
You need Except : f[a : Except[_Integer]] := 2 a In addition to being concise, this has an advantage that you can use it in functions which hold their arguments, and don't need to worry about evaluation leaks, since this test is done entirely by the pattern-matcher. For this reason, this is also more efficient than testing head explicitly.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/35261",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10347/"
]
}
|
35,371 |
I am handling large numerical data in Mathematica . In smaller problems everything worked fine using Export and Import with the parameter csv and nothing more. Now I am facing a much larger data volume and plain Export and Import is way too slow for CSV format. What I want to do: First, exporting a numerical list of approximately $1400 \cdot 260$. Then I perform some calculations outside of mathematica and finally I import a csv file back using Import . In this question I read how to improve the speed of Export with CSV. I tried Export["data.csv",
ExportString[Transpose[temp], "CSV", "FieldSeparators" -> ", "],
"Table"]; for a toy-example of dimension $9 \cdot 6$. This could be temp = RandomReal[{0, 1000}, {9, 6}]; The problem is that I got additional blank lines in my CSV file. How can I avoid those blank lines? I did not have them using plain Export . Second part of the question: can I use a similar approach to speed up Import for CSV files? I work in English locale in Windows 7 and Mathematica 8. My data should be comma-separated. The result of the above looks like this: 155.9418457227914,427.72566448956945,462.4370455183139,434.230107096781,377.73423736605037,457.7044624877774,229.5721937681028,453.6973831247924,827.5146478718962
656.9573702857699,975.1048399942904,716.715190156526,67.07781324817643,168.78248854317894,863.1953962590844,997.7580107302701,427.94798294100747,565.2955778916687
192.3648037459477,435.0418975785194,126.17228368369842,772.0737083559297,453.73573640921836,957.9178360741387,920.4158275934401,234.75353158374764,162.82606110943834
841.7132070637356,799.1268178998612,931.2448706410551,950.7753472229233,114.01596316796622,145.0771999411104,287.47149951303663,786.9008107323455,99.09420650484662
116.9916885502289,715.7594598282562,970.6252946068753,654.1742185278038,262.3778046629968,200.13980161337577,347.24862854841354,314.5612015073982,241.11046402342163
203.65015448763597,952.1236458849723,578.2673369638862,527.2990305555661,655.1228742370724,318.81372163827496,311.2738362265584,315.97629887850667,514.7676854642548 EDIT:
A small example of the data that I want to import (2nd step) can be found here .
The true problem size is here .
|
Here's a much faster, purely Mathematica way than using Import to import your data: UPDATE As Leonid mentioned the previous code doesn't exactly replicate Import . The truth is I was only trying to retrieve the numerical part. Here's an updated version that tries to replicate the output from Import . readYourCSV2[file_String?FileExistsQ, n_Integer] := Module[{str = OpenRead[file], data},
data = ReadList[str, Table[Record, {n}], RecordSeparators -> {",", "\n"}];
Close[str];
ReleaseHold[ToExpression[data, InputForm, Hold] /. {Plus[Times[x_, E | e], y_] :> x * 10 ^ y}]
] Here, n is the number of columns. UPDATE 2 Now for the Export , here's a fast, again, purely Mathematica way to export in CSV format. writeYourCSV[file_String, list_List?MatrixQ] :=
With[{str = OpenWrite[file, PageWidth -> Infinity], len = Length[ list[[1]] ]},
Scan[Write[str, Sequence @@ (Flatten[Table[{FortranForm[ #[[i]] ], OutputForm[","]},
{i, len - 1}]]) ~ Join ~ { FortranForm[ #[[len]] ] }] &, list]; Close[str];
] This takes less than 10 seconds to write your large data back to CSV format: writeYourCSV["testcsv.csv", databig] // AbsoluteTiming {9.921969, Null}
|
{
"source": [
"https://mathematica.stackexchange.com/questions/35371",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10385/"
]
}
|
35,505 |
Note: Please see comments below @bobthechemist's answer for why question was edited. I've made a video of two teams playing soccer. Now I would like to translate each soccer-player to a (x,y) coordinate and follow them during the match. I know that Mathematica has some image feature tracking and am looking for a suggested workflow for image analysis and an example of how to apply it to a series of images. Has anybody experience with video and image recognition? I've made a video of two teams playing soccer. Now I would like to translate each soccer-player to a (x,y) coordinate and follow them during the match.
|
Well, I suspect this question will get closed because it is a bit broad, but I've played around with image tracking and thought I'd show what I've done in case it's helpful. I was interested in learning some physics, and have the following video: To do the tracking, I smoothed out the images and converted them to black and white, which allows for the colored balls to who up on a black background. Note that I have already defined the symbol images which was the series of graphics that made up the video. imagesbw = Binarize[MedianFilter[Image[ImageData[#][[All,All,1]]],4]]&/@images; We lose the black ball, which is unfortunate, but my "physics question" was to see if I could predict the movement of the missing black ball from the information that is available. I started by collecting the position of the three visible balls using ComponentMeasurements which in my case finds four balls, one of which is the one in the upper right hand corner that doesn't move, so I'll ignore it. I can then get tracking information from the ComponentMeasurements output. Note I did play around with ImageFeatureTrack, but I didn't have much luck with it. movement = ComponentMeasurements[#, "BoundingDiskCenter"] & /@ imagesbw;
tracking =
Graphics@Riffle[{Red, Orange, Blue, Red},
Point[Cases[# /. movement, x_ /; Dimensions[x] == {2}]] & /@
Range[4]] There's some messiness in the data, so the line above deletes some of the points. Now I want to predict where the 8-ball is heading from the information in the point plot above. I approach this problem by assuming conservation of momentum assuming an elastic collision, ignoring friction and acceleration. There's a reason why my name isn't bobthephysicist. There's probably no real reason to go through my ugly code to solve this problem, especially since I did so by surfing around Mathematica.SE so the solutions are already here. At the end of the day, I get the following graphic, which is a pretty decent fit, although I will admit I did need to incorporate a fudge factor in to the solution. My assumptions, as well as my not knowing the weights of the four objects, makes this task a bit daunting. So in summary, tracking objects in Mathematica is possible, but it's not for the faint of heart. I think the process is summarized in the following steps: Import video as individual frames, possibly "downsampling" the video to make the data set manageable. Manipulating the images to remove extraneous information (colors, stationary objects, etc.) Use some tool such as MorphologicalComponents to identify the information of interest to you. Transform the output of the previous step into a usable format That's my 2 cents -
|
{
"source": [
"https://mathematica.stackexchange.com/questions/35505",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9590/"
]
}
|
35,653 |
In this example, how can I put the legend inside the graph? Currently, when I save the graph, only the graph is saved, not the legend. Expr1 = -2 p + 1
Expr2 = 2 p - 1
Expr3 = p - 1/2
Plot[{Expr1, Expr2, Expr3}, {p, 0, 1},
BaseStyle -> AbsoluteThickness[4],
PlotLegends ->
LineLegend["Expressions", BaseStyle -> AbsoluteThickness[4]]]
Solve[Expr1 == Expr2, p] Also, how can I insert the solution in the last line, also inside the graph? Here you can see the result:
|
This is how to save the graph, legend and all: Another way would be to use Rasterize : Rasterize[Plot[...]] The legend and the graph is now one image.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/35653",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6543/"
]
}
|
35,683 |
I used the following code to find the volume of the sphere $x^2+y^2+z^2 \leq 1$ in the first octant: McVolume[Num_] :=
Module[{hit, miss, index, x, y, z}, hit = 0; miss = 0;
For[index = 1, index <= Num, index = index + 1,
x = Random[Real, {0, 1}];
y = Random[Real, {0, 1}];
z = Random[Real, {0, 1}];
If[z <= Sqrt[1 - x^2 - y^2], hit = hit + 1, miss = miss + 1];];
Return[(hit/Num) 1];]
McVolume[100] It turns out to be 11/25 . Even thought the answer is correct but using this code i am getting an error: LessEqual::nord: Invalid comparison with 0. +0.48202 I attempted. >> I don't understand, why is this error popping up? Any help would be appreciated.
|
The programming style you are using is not very fitting for Mathematica. Here's a better way (shorter, much faster): n = 1000000; (* number of points to use *)
octantVolume = N[ Total@UnitStep[1 - Norm /@ RandomReal[1, {n, 3}]]/n ] The reason why you get the error you mention is that for some x , y , the expression 1 - x^2 - y^2 is negative, thus its square root is not a real number and can't be use in inequalities. Use If[x^2+y^2+z^2 <= 1^2, ...] instead.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/35683",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10386/"
]
}
|
36,792 |
I need to play with a lot of powers such as 10^-3 . 1E-3 does not work for it. Is there any short form for it?
|
I'm surprised there isn't a question about this ( i.e. entering numbers in scientific notation) already. To enter $3\times10^{-3}$, you can write 3*^-3 . For further reference, see Input Syntax: Numbers .
|
{
"source": [
"https://mathematica.stackexchange.com/questions/36792",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2000/"
]
}
|
36,830 |
I was recently faced with the task of creating a DensityPlot with a logarithmic colour scale, and with providing it with an appropriate legend. Since I could not find any resources to this effect on this site, I'd like to document my solution here. For definiteness, suppose that I want a plot of the function
$$
f(x,y)=\mathrm{sinc}^2(x)\mathrm{sinc}^2(y)=\frac{\sin^2(x)\sin^2(y)}{x^2y^2},
$$
which is the diffraction pattern of a square aperture , over a box of side 20. The problem with such a function, and the reason a logarithmic scale is necessary, is that the function has lots of detail over a wide range of orders of magnitude of $f$. Thus, doing a naive DensityPlot of it will produce either whited-out parts with a sharp boundary with the region where the contrast is acceptable, or one bright spot and lots of detail completely lost: (Images produced by DensityPlot[Sinc[x]^2 Sinc[y]^2, {x, -20, 20}, {y, -20, 20},
ColorFunction -> ColorData["DeepSeaColors"], PlotPoints -> 100, PlotRange -> u] for u set to Automatic and Full respectively.) Because of this, and particularly for plotting a function that has a zero, any solution to this problem must take as arguments the minimum and the maximum values of the range of interest. That range of interest is intrinsically hard-to-impossible for an automated range finder to obtain, so I'm OK with having to supply those values by hand. To give a more concrete example of what the goal is, let me nick the final image from my answer:
|
Giving the density plot a logarithmic scale must always involve - unless some future version of Mathematica includes it by default - overriding the ColorFunctionScaling of the original plotting command and supplying a custom scaling function. The simplest logarithmic scaling is of the form
$$
\mathrm{scaling}(x)=\frac{\log(x/\mathrm{min})}{\log(\mathrm{max}/ \mathrm{min})},
$$
which is given the parameters $\rm min$ and $\rm max$, and maps them respectively to 0 and 1, which are the limits of the standard input range of any colour function. This scaling function is implemented as LogarithmicScaling[x_, min_, max_] := Log[x/min]/Log[max/min] To include this in the plotting command, one needs to set ColorFunctionScaling to False , and supply LogarithmicScaling to some appropriate ColorFunction , which looks like plotter[min_, max_] := DensityPlot[Sinc[x]^2 Sinc[y]^2, {x, -20, 20}, {y, -20, 20}
, PlotPoints -> 100, PlotRange -> Full
, ColorFunctionScaling -> False
, ColorFunction -> (ColorData["DeepSeaColors"][LogarithmicScaling[#, min, max]] &)
]
plotter[0.00003, 1] and produces Getting the legend to work, on the other hand, is more tricky. The standard way to include a legend for a DensityPlot is to set some nontrivial option for PlotLegends ; as the examples on the DensityPlot documentation show, the Automatic setting usually does a good job. For a logarithmic scale, on the other hand, the resulting BarLegend needs to be modified. More specifically, the colour function provided to BarLegend must vary linearly with the input it is given (which goes linearly from bottom to top of the scale), and it is the ticks themselves that must be rescaled. This requires the inverse of the $\rm scaling$ function, which is given by
$$
x=\mathrm{min} \left({\mathrm{max}}\over{ \mathrm{min}}\right)^{\mathrm{scaling}(x)}.
$$
The strategy is to find those values of $x$ for which $\rm{scaling}(x)$ is 0, 1, and a given number of values evenly spread between the two. Thus: We set PlotLegends to BarLegend , we give BarLegend the unadulterated colour function we gave to the DensityPlot , we tell BarLegend to take 0 and 1 as the minimum and maximum values to be fed to the colour function, to generate the full colour spectrum linearly, we generate the list of positions of the ticks using min (max/min)^(Range[0, 1, 1/NumberOfTicks]) , we generate the colour-function-input they correspond to, and their labels, by mapping {LogarithmicScaling[#, min, max], ScientificForm[#, 2]} & over that list, and we feed that to the Ticks option of BarLegend . The resulting code looks like plotter[min_, max_, NumberOfTicks_] := DensityPlot[Sinc[x]^2 Sinc[y]^2
, {x, -20, 20}, {y, -20, 20}
, PlotPoints -> 100, PlotRange -> Full
, ColorFunctionScaling -> False
, ColorFunction -> (ColorData["DeepSeaColors"][LogarithmicScaling[#, min, max]] &)
, PlotLegends -> BarLegend[{ColorData["DeepSeaColors"], {0, 1}}, LegendMarkerSize -> 370
, Ticks -> ({LogarithmicScaling[#, min, max], ScientificForm[#, 2]} & /@ (
min (max/min)^Range[0, 1, 1/NumberOfTicks]))]
]
plotter[0.00003, 1, 5] and produces output like The highlighter colours the Ticks option inside BarLegend in red, but it works just fine as far as I can tell. The error class this is assigned to (visible e.g. by changing the colour setting in Edit > Preferences > Appearance > Syntax Coloring > Errors and Warnings ) is "Unrecognized option names". I don't think this is particularly bad, but rather reflects the fact that the highlighter is not perfect , and should not really be expected to be. Addendum: minor ticks. While the above is perfectly fine, the ticks do not make it immediately clear that the scale is logarithmic in the way that appropriately placed minor ticks will do. To implement these, the best option is to take advantage of the built-in capability to make nice ticks in log scale plots. The essential part of this is to extract, using AbsoluteOptions , the Ticks of an appropriate LogPlot . Unfortunately, the linearized coordinates of the ticks are rather inconveniently placed, and have an arbitrary linear scale of their own. The code below is therefore rather long, but I've made it verbose so that hopefully it's clear what's going on. LogScaleLegend[min_, max_, colorfunction_, height_: 400] := Module[
{bareTicksList, numberedTicks, m, M, ml, Ml, minInArbitraryScale,
maxInArbitraryScale, linearScaling},
bareTicksList =
First[Ticks /. AbsoluteOptions[LogLogPlot[x, {x, min, max}]]];
numberedTicks = (
Select[
bareTicksList /. {Superscript -> Power},
NumberQ[#[[2]]] &
]
)[[All, {1, 2}]];
m = Min[numberedTicks[[All, 2]]];
M = Max[numberedTicks[[All, 2]]];
ml = Min[numberedTicks[[All, 1]]];
Ml = Max[numberedTicks[[All, 1]]];
{minInArbitraryScale, maxInArbitraryScale} =
ml + (Ml - ml) Log[{min, max}/m]/Log[M/m];
linearScaling[x_] := (x - minInArbitraryScale)/(
maxInArbitraryScale - minInArbitraryScale);
DensityPlot[y
, {x, 0, 0.04}, {y, 0, 1}
, AspectRatio -> Automatic, PlotRangePadding -> 0
, ImageSize -> {Automatic, height}
, ColorFunction -> colorfunction
, FrameTicks -> {{None,
Select[
Table[{
linearScaling[r[[1]]],
r[[2]] /. {Superscript[10., n_] -> Superscript[10, n]},
{0, If[r[[2]] === "", 0.15, 0.3]},
{If[r[[2]] === "", Thickness[0.03], Thickness[0.06]]}
}, {r, bareTicksList}]
, (#[[1]] (1 - #[[1]]) >= 0 &)]
}, {None, None}}
]
] With this function, then, the code plotter[min_, max_, NumberOfTicks_] := DensityPlot[
Sinc[x]^2 Sinc[y]^2
, {x, -20, 20}, {y, -20, 20}
, PlotPoints -> 100
, PlotRange -> Full
, ColorFunctionScaling -> False
, ColorFunction -> (ColorData["DeepSeaColors"][
LogarithmicScaling[#, min, max]] &)
, PlotLegends ->
LogScaleLegend[min, max, ColorData["DeepSeaColors"], 350]
]
plotter[0.00003, 1, 5] produces the output
|
{
"source": [
"https://mathematica.stackexchange.com/questions/36830",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1000/"
]
}
|
36,847 |
I want to form the function $h=f-\lambda_{1}g_{1}-\lambda_{2}g_{2}$ where $f$ is the function to optimize subject to the constraints $g_{1}=0$ and $g_{2}=0$ so that I can solve the first partial derivatives with respect to $\lambda_{1}$ and $\lambda_{2}$. Can someone get me started using $f(x,y,z)=xy+yz$ subject to the constraints $x^2+y^2-2=0$ and $x^2+z^2-2=0$?
|
We define the function f and multiple constraint functions g1 , g2 : f[x_, y_, z_] := x y + y z
g1[x_, y_] := x^2 + y^2 - 2
g2[x_, z_] := x^2 + z^2 - 2 then, in order to find necessary conditions for constrained extrema we introduce the Lagrange function h with Lagrange multipliers λ1 and λ2 : h[x_, y_, z_, λ1_, λ2_] := f[x, y, z] - λ1 g1[x, y] - λ2 g2[x, z] Now we solve an appropriate system of equations satisfying necesary conditions (i.e. vanishing of all first derivatives of h ): TraditionalForm[
Column[ pts = {x, y, z} /.
FullSimplify @ Solve[ D[h[x, y, z, λ1, λ2], #] == 0 & /@ {x, y, z, λ1, λ2},
{x, y, z, λ1, λ2}], Frame -> All]] A bit nicer way of finding all the solutions uses Grad - a new function in Mathematica 9 for vector analysis: {x, y, z} /. Solve[ Grad[ h @@ #, #] == 0, #]& @ {x, y, z, λ1, λ2} // FullSimplify The above table contains all critical points of the Lagrange function h . For sufficient conditions one can use Maximize and Minimize , e.g.: FullSimplify @ ToRadicals @
Maximize[{f[x, y, z], g1[x, y] == 0, g2[x, z] == 0}, {x, y, z}] {1 + Sqrt[2], {x -> -(1/Sqrt[2 + Sqrt[2]]),
y -> -Sqrt[1 + 1/Sqrt[2]],
z -> -Sqrt[1 + 1/Sqrt[2]]}} We add a graphics with contours of constrained minima and maxima, the contraint functions ass well as all critical points of h : Show[
ContourPlot3D[{ f[x, y, z] == 1 + Sqrt[2],
f[x, y, z] == -1 - Sqrt[2],
g1[x, y] == 0, g2[x, z] == 0},
{x, -2.3, 2.3}, {y, -2.3, 2.3}, {z, -2.3, 2.3},
ContourStyle -> {Directive[Cyan, Opacity[0.5]],
Directive[Green, Opacity[0.5]],
Directive[Orange, Opacity[0.15]],
Directive[Orange, Opacity[0.15]]}, Mesh -> None],
Graphics3D[{Magenta, PointSize[0.015], Point[pts]}]] On the cyan surfaces we have maxima, on the green ones - minima and the solutions of the necessary conditions are denoted with the magenta points lying on the tube constraints.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/36847",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10227/"
]
}
|
36,867 |
I have two sorted lists, one list will be called the "fences" and the other the "values" Fences could be: $\{1, 5, 9, 14\}$ Values could be $\{-1, 1, 3, 4, 6, 9, 10, 13, 14, 15\}$ I want to partition the values list using the equivalence relation that they are between the same fence values. ($f_i \leq v < f_{i+1})$ With the example above, I would get the partition: $$\{\{-1\}, \{1,3,4\}, \{6\}, \{9, 10, 13\}, \{14,15\}\}$$ This partitioning is quite easy using to implement using a for loop but I can't help but feel there is a better way to do it using some of the inbuilt Mathematica functions. I am not asking anyone to write the algorithm for me but to suggest which functions I should be aware of in order to do this elegantly.
|
f = {1, 5, 9, 14};
v = {-1, 1, 3, 4, 6, 9, 10, 13, 14, 15};
BinLists[v, {Join[{-Infinity}, f, {Infinity}]}] {{-1}, {1, 3, 4}, {6}, {9, 10, 13}, {14, 15}}
|
{
"source": [
"https://mathematica.stackexchange.com/questions/36867",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6143/"
]
}
|
37,207 |
I am new to Mathematica and have recently been exploring graphical animations. So I was experimenting with simple concepts in periodic motion and hence wondered how can I draw a simple spring? Is there an easier/better way to do this? The solution I arrived at was a simple function to draw a spring between two $x$ and $y$ coordinates. hspring[a0_, x10_, x20_] :=
Module[{a = a0, x1 = x10, x2 = x20, n = 100},
h = (x2 - x1)/n;
xvalues = Table[k, {k, x1, x2, h}];
yvalues = Table[a Sin[m Pi/2], {m, 0, n}];
Line[Transpose @ {xvalues, yvalues}]
];
vspring[a0_, y10_, y20_] :=
Module[{a = a0, y1 = y10, y2 = y20, n = 100},
h = (y2 - y1)/n;
yvalues = Table[k, {k, y1, y2, h}];
xvalues = Table[a Sin[m Pi/2], {m, 0, n}];
Line[Transpose @ {xvalues, yvalues}]
];
Manipulate[
Graphics[{hspring[0.2, 0, Abs[2 Sin[x]]], Red, PointSize[0.03],
Point[{Abs[2 Sin[x]], 0}]}, PlotRange -> {{0, 3}, {-1, 1}}],
{x, 0.01, 2 Pi, 0.1}]
|
A textbook-like animation turns = 10;
aa = Table[Framed@
Show[ParametricPlot3D[
Piecewise[{{{1, x, 0}, x <= 0},
{{Cos[2 Pi turns x/r], x, Sin[2 Pi turns x/r]}, 0 < x <= r},
{{1, x, 0}, x > r}}],
{x, -.5, r + .5},
PlotStyle -> {Gray, Specularity[Gray, 10]}, Lighting -> "Neutral",
PlotPoints -> 100, MaxRecursion -> 3,
PlotRange -> {{-10, 10}, {-1, 15}, {-5, 5}},
Axes -> None, Boxed -> False, Method -> {"TubePoints" -> 30},
ViewPoint -> {10000, 1, 5}] /. Line[pts_, rest___] :> Tube[pts, 0.2, rest],
Graphics3D[Sphere[{1, r + 1, 0}, 1.25]]], {r, Table[15/2 - 5/2 Cos@x, {x, 0, Pi, .1}]}];
Export["C:\\test.gif", Join[aa, Reverse@aa]]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37207",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5570/"
]
}
|
37,213 |
I have a stack of tiff files. When imported to Mathematica , they form a $P \times M \times N$ matrix, where $P$ is the number of single images in the stack, $M$ is the number of horizontal pixels and $N$ vertical pixels. I want to calculate the covariance of each vector $P_{mn}$ with the rest of the vectors, where $ m $ and $n$ go from 1 to $ M $ and $N$ respectively. In the end, I should have $M*N$ matrices with dimension $M \times N$. To get an idea of the data size, I will give some numbers $P\geq50 000$, $M=N=20$.
|
A textbook-like animation turns = 10;
aa = Table[Framed@
Show[ParametricPlot3D[
Piecewise[{{{1, x, 0}, x <= 0},
{{Cos[2 Pi turns x/r], x, Sin[2 Pi turns x/r]}, 0 < x <= r},
{{1, x, 0}, x > r}}],
{x, -.5, r + .5},
PlotStyle -> {Gray, Specularity[Gray, 10]}, Lighting -> "Neutral",
PlotPoints -> 100, MaxRecursion -> 3,
PlotRange -> {{-10, 10}, {-1, 15}, {-5, 5}},
Axes -> None, Boxed -> False, Method -> {"TubePoints" -> 30},
ViewPoint -> {10000, 1, 5}] /. Line[pts_, rest___] :> Tube[pts, 0.2, rest],
Graphics3D[Sphere[{1, r + 1, 0}, 1.25]]], {r, Table[15/2 - 5/2 Cos@x, {x, 0, Pi, .1}]}];
Export["C:\\test.gif", Join[aa, Reverse@aa]]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37213",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5589/"
]
}
|
37,266 |
Today, I found the Euler Project. Problem #2 is Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. I have two solutions: For[i = 1, i < 100, i++, If[Fibonacci[i] > 4000000, Break[]]];
Plus @@ Select[Fibonacci /@ Range[i - 1], Mod[#, 2] == 0 &] 4613732 Plus @@ Select[
Fibonacci /@ Select[Range@100, Fibonacci@# < 4000000 &],
Mod[#1, 2] == 0 &] 4613732 However, I feel my solutions are not good and efficient. So my question is: can you show me more concise and efficient methods? Also, how cam I test whether a number is a Fibonacci number?
|
The other methods described work well, but I am partial to exact answers. So, here it is. First, note that the Fibbonacci sequence has a closed form $$F_n = \frac{\Phi^n - (-\Phi)^{-n}}{\sqrt{5}}$$ where $\Phi$ is the GoldenRatio . Also, as observed elsewhere, we are looking only at every third term, which gives the sum $$\sum^k_{n = 1} \frac{\Phi^{3n} - (-\Phi)^{-3n}}{\sqrt{5}}$$ which is just the sum of two geometric series . So, after a few steps, this simplifies to $$\frac{1}{\sqrt{5}} \left[ \Phi^3\frac{1 - (\Phi^3)^{k}}{1-\Phi^3} + \Phi^{-3}\frac{1 - (-\Phi^{-3})^{k}}{1 + \Phi^{-3}} \right]$$ where $k$ is the index of the highest even Fibbonacci number. To find $k$, we can reverse the sequence , n[F_] := Floor[Log[F Sqrt[5]]/Log[GoldenRatio] + 1/2]
n[4000000]
(* 33 *) So, $k = 11$. In code, Clear[evenSum];
evenSum[(k_Integer)?Positive] :=
Round @ N[
With[
{phi = GoldenRatio^3, psi = (-GoldenRatio)^(-3)},
(1/Sqrt[5])*(phi*((1 - phi^k)/(1 - phi)) - psi*((1 - psi^k)/(1 - psi)))
],
Max[$MachinePrecision, 3 k] (* needed for accuracy *)
]
evenSum[11]
(* 4613732 *) which is confirmed by Total @ Fibonacci @ Range[3, 33, 3]
(* 4613732 *) Edit : The above implementation of n suffers round off problems for large numbers, for example n[9000] gives 21, but Fibonacci[21] is 10946. But, wikipedia gives a better choice Clear[n2];
n2[fn_Integer?Positive] :=
Floor@N@Log[GoldenRatio, (fn Sqrt[5] + Sqrt[5 fn^2 - 4])/2]
n2[10945]
(* 20 *)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37266",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9627/"
]
}
|
37,380 |
I do have noisy data and want to smooth them by a Savitzky-Golay filter because I want to keep the magnitude of the signal. a) Is there a ready-to-use Filter available for that? b) what are appropriate values for m (the half width) and for the coefficients for 3000-4000 data points?
|
The following code will filter noisy data… SGKernel[left_?NonNegative, right_?NonNegative, degree_?NonNegative, derivative_? NonNegative] :=
Module[{i, j, k, l, matrix, vector},
matrix = Table[ (* matrix is symmetric *)
l = i + j;
If[l == 0,
left + right + 1,
(*Else*)
Sum[k^l, {k, -left, right}]
],
{i, 0, degree},
{j, 0, degree}
];
vector = LinearSolve[
matrix,
MapAt[1&, Table[0, {degree+1}], derivative+1]
];
(* vector = Inverse[matrix][[derivative + 1]]; *)
Table[
vector.Table[If[i == 0, 1, k^i], {i, 0, degree}],
{k, -left, right}
]
] /; derivative <= degree <= left+right
SGSmooth[list_?VectorQ, window_, degree_, derivative_:0]:=
Module[{pairs},
pairs = MapThread[List, {Range[Length[list]], list}];
Map[Last, SGSmooth[pairs, window, degree, derivative]]
]
SGSmooth[list_?MatrixQ, window_, degree_, derivative_:0]:=
Module[{kernel, list1, list2, margin, space, smoothData},
(* determine a symmetric margin at the ends of the raw dataset.
The window width is split in half to make a symmetric window
around a data point of interest *)
margin = Floor[window/2];
(* take only the 1st column of data in the list to be smoothed (the
independant Values) and extract the data from the list by removing
half the window width 'i.e., margin' from the ends of the list *)
list1 = Take[Map[First, list], {margin + 1, Length[list] - margin}];
(* take only the 2nd column of data in the list to be smoothed
(the dependent Values) and Map them into list2 *)
list2 = Map[Last, list];
(* get the kernel coefficients for the left and right margins, the
degree, and the requested derivative *)
kernel = SGKernel[margin, margin, degree, derivative];
(* correlation of the kernel with the list of dependent values *)
list2 = ListCorrelate[kernel, list2];
(* Data _should_ be equally spaced, but... calculate spacing anyway by getting
the minimum of all the differences in the truncated list1, remove the first
and last points of list1 *)
space = Min[Drop[list1, 1] - Drop[list1, -1]];
(* condition the dependant values based on spacing and the derivative *)
list2 = list2*(derivative!/space^derivative);
(* recombine the correlated (x-y) data pairs (that is list1 and list2),
put these values back together again to form the smooth data list *)
smoothData=Transpose[{list1, list2}]
] /; derivative <= degree <= 2*Floor[window/2] && $VersionNumber >= 4.0 I did not apply this to your data, but you can do that later. This example is applied to noisy random data. Using a noisy sine data function… dataFunction[x_] := Sin[x] + Random[Real, {-π, π}]; Build a table of noisy tabular data from $0$ to $2\pi$… dataTable = Table[{x, dataFunction[x]}, {x, 0, 2 π, .01}]; Animate the smoothing operations. Notice the smoothed dataset shrinks with increasing 'window width'. This is an artifact of the ListCorrelate function used in the SGSmooth function. ListCorrelate uses an end buffered dataset. NOTE: The red line is the filtered data set… Manipulate[
If[showRawData,
Show[
ListPlot[dataTable, PlotRange -> {{0, 2 π}, {-5.0, 5.0}}],
ListPlot[
{
SGSmooth[dataTable, win, order]
},
PlotRange -> {{0, 2 π}, {-5.0, 5.0}},
PlotStyle -> {{Red, Thick}, {Green, Thick}},
Joined -> True]
], (* ELSE just plot smooth data *)
ListPlot[
{
SGSmooth[dataTable, win, order]
},
PlotRange -> {{0, 2 π}, {-5.0, 5.0}},
PlotStyle -> {{Red, Thick}, {Green, Thick}},
Joined -> True]
],
{{win, 100, "window width"}, 2, 300, 1,
Appearance -> "Labeled"}, {{order, 1, "order of polynomial"}, 1, 9,
1, Appearance -> "Labeled"},
{{showRawData, True, "Raw Data"}, {True, False}},
SaveDefinitions -> True
] This will create a Manipulate similar to the following: Hope this helps!
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37380",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7177/"
]
}
|
37,381 |
The scrap of code below [from Mathematica's Help on DynamicModules ] generates a Pane of Locator s, and a line showing the interpolation between the datapoints. DynamicModule[{pts = {{0, 0}, {1, 1}, {2, 0}, {3, 2}}},
LocatorPane[Dynamic[pts],
Dynamic[Plot[InterpolatingPolynomial[pts, x], {x, 0, 3},
PlotRange -> 3]
]]] When the program is saved,and reloaded, the Plot persists with the then current values of the points. Suppose, after reloading the file (but not reinitializing the DynamicModule ), I want to use the values of the points (which I moved in interacting with the program before saving it). In otherwords, I'd like to be able to access a list of the modified points with, perhaps, new functions. I realize I could just read out variables in the original function, store them, then load them as part of the initialization procedure when restarting a program a second time, but this in effect means running the original program history completely again. In complex programs, with lots of potential branches, this could be tedious and error prone. Any solution? DynamicModule would seem to attempt to address this problem by saving variables, but, for example, in the above code scrap, I want to get numerical values of the point positions for use in other parts of the program, how would I do it?
|
The following code will filter noisy data… SGKernel[left_?NonNegative, right_?NonNegative, degree_?NonNegative, derivative_? NonNegative] :=
Module[{i, j, k, l, matrix, vector},
matrix = Table[ (* matrix is symmetric *)
l = i + j;
If[l == 0,
left + right + 1,
(*Else*)
Sum[k^l, {k, -left, right}]
],
{i, 0, degree},
{j, 0, degree}
];
vector = LinearSolve[
matrix,
MapAt[1&, Table[0, {degree+1}], derivative+1]
];
(* vector = Inverse[matrix][[derivative + 1]]; *)
Table[
vector.Table[If[i == 0, 1, k^i], {i, 0, degree}],
{k, -left, right}
]
] /; derivative <= degree <= left+right
SGSmooth[list_?VectorQ, window_, degree_, derivative_:0]:=
Module[{pairs},
pairs = MapThread[List, {Range[Length[list]], list}];
Map[Last, SGSmooth[pairs, window, degree, derivative]]
]
SGSmooth[list_?MatrixQ, window_, degree_, derivative_:0]:=
Module[{kernel, list1, list2, margin, space, smoothData},
(* determine a symmetric margin at the ends of the raw dataset.
The window width is split in half to make a symmetric window
around a data point of interest *)
margin = Floor[window/2];
(* take only the 1st column of data in the list to be smoothed (the
independant Values) and extract the data from the list by removing
half the window width 'i.e., margin' from the ends of the list *)
list1 = Take[Map[First, list], {margin + 1, Length[list] - margin}];
(* take only the 2nd column of data in the list to be smoothed
(the dependent Values) and Map them into list2 *)
list2 = Map[Last, list];
(* get the kernel coefficients for the left and right margins, the
degree, and the requested derivative *)
kernel = SGKernel[margin, margin, degree, derivative];
(* correlation of the kernel with the list of dependent values *)
list2 = ListCorrelate[kernel, list2];
(* Data _should_ be equally spaced, but... calculate spacing anyway by getting
the minimum of all the differences in the truncated list1, remove the first
and last points of list1 *)
space = Min[Drop[list1, 1] - Drop[list1, -1]];
(* condition the dependant values based on spacing and the derivative *)
list2 = list2*(derivative!/space^derivative);
(* recombine the correlated (x-y) data pairs (that is list1 and list2),
put these values back together again to form the smooth data list *)
smoothData=Transpose[{list1, list2}]
] /; derivative <= degree <= 2*Floor[window/2] && $VersionNumber >= 4.0 I did not apply this to your data, but you can do that later. This example is applied to noisy random data. Using a noisy sine data function… dataFunction[x_] := Sin[x] + Random[Real, {-π, π}]; Build a table of noisy tabular data from $0$ to $2\pi$… dataTable = Table[{x, dataFunction[x]}, {x, 0, 2 π, .01}]; Animate the smoothing operations. Notice the smoothed dataset shrinks with increasing 'window width'. This is an artifact of the ListCorrelate function used in the SGSmooth function. ListCorrelate uses an end buffered dataset. NOTE: The red line is the filtered data set… Manipulate[
If[showRawData,
Show[
ListPlot[dataTable, PlotRange -> {{0, 2 π}, {-5.0, 5.0}}],
ListPlot[
{
SGSmooth[dataTable, win, order]
},
PlotRange -> {{0, 2 π}, {-5.0, 5.0}},
PlotStyle -> {{Red, Thick}, {Green, Thick}},
Joined -> True]
], (* ELSE just plot smooth data *)
ListPlot[
{
SGSmooth[dataTable, win, order]
},
PlotRange -> {{0, 2 π}, {-5.0, 5.0}},
PlotStyle -> {{Red, Thick}, {Green, Thick}},
Joined -> True]
],
{{win, 100, "window width"}, 2, 300, 1,
Appearance -> "Labeled"}, {{order, 1, "order of polynomial"}, 1, 9,
1, Appearance -> "Labeled"},
{{showRawData, True, "Raw Data"}, {True, False}},
SaveDefinitions -> True
] This will create a Manipulate similar to the following: Hope this helps!
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37381",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6712/"
]
}
|
37,480 |
In the documentation, it states that The Laplace transform of a function $f(t)$ is defined to be
$\int_0^{\infty } f(t) e^{-s t} \, \mathrm{d}t$. But why can Mathematica not get the Laplace transform of $\frac{1-\cos (t)}{t}$? $Assumptions=s>0;
LaplaceTransform[(1-Cos[t])/t,t,s]
(* EulerGamma+LaplaceTransform[1/t,t,s]+1/2 Log[1+s^2] *) and the integral does converge Integrate[(1-Cos[t])/t Exp[-s t],{t,0,∞}]
(* 1/2 Log[1+1/s^2] *) ?
|
You can use a trick to prevent Mathematica from taking your expression apart: LaplaceTransform[Abs[1 - Cos[t]]/t, t, s]
(* 1/2 Log[1 + 1/s^2] *)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37480",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1364/"
]
}
|
37,557 |
I am trying to figure out what the announcement of the Wolfram Language means for Mathematica. Is Mathematica an implementation of the Wolfram Language, or is it something else?
|
The Wolfram Language is what we all know as Mathematica, but rebranded to help wider adoption to people, particularly for people who don't think of themselves as "math" people. As a Mathematica programmer, emphasis on the "programmer", I see this as a good thing.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37557",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/2469/"
]
}
|
37,698 |
The surface show below is very beautiful; however, I don't know its function either as an implicit function or in parametric form. Anyone have an idea about it and how to draw it with Mathematica ?
|
Consider this: ParametricPlot3D[
RotationTransform[a, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}],
{a, 0, 2 Pi}, Evaluated -> True] Now rotate this around a circle, while rotating it at the same time around its' origin: ParametricPlot3D[
RotationTransform[b, {0, 0, 1}][{6, 0, 0} +
RotationTransform[a + 3 b, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}]],
{a, 0, 2 Pi}, {b, 0, 2 Pi}, PlotPoints -> 40, Evaluated -> True] EDIT: A color function, omitting surface mesh, fixing direction of rotation and adding a hint of transparency, like the original: ParametricPlot3D[
RotationTransform[b, {0, 0, 1}][{6, 0, 0} +
RotationTransform[a - 3 b + Pi, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}]],
{a, 0, 2 Pi}, {b, 0, 2 Pi}, PlotPoints -> 40,
ColorFunction -> (RGBColor[#, 0, 1 - #, 4/5] &[1/2 + {1, -1}.{#1, #2}/2] &),
Mesh -> False, Evaluated -> True] This might be slightly more intuitive way to write ColorFunction using Blend and Opacity in PlotStyle : ParametricPlot3D[
RotationTransform[b, {0, 0, 1}][{6, 0, 0} +
RotationTransform[a - 3 b + Pi, {0, 1, 0}][{0, 0, Sin[3 a] + 5/4}]],
{a, 0, 2 Pi}, {b, 0, 2 Pi},
PlotPoints -> 40,
PlotStyle -> Opacity[4/5],
ColorFunction -> (Blend[{Red, Blue}, 1/2 + {1, -1}.{#1, #2}/2] &),
Mesh -> False, Evaluated -> True]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37698",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9851/"
]
}
|
37,888 |
At my university, I have a yearly essay. I'm allowed to use any technology for implementing it. I've been coding it in C++ with Qt. I thought of about Wolfram Mathematica because I have some experience in it. I need such functionality: Timers — for calling functions by timer Threads (or Processes are good too) User-friendly GUI (buttons, input forms) Be able to catch when user clicked left/right mouse buttons or key on keyboard Dynamic graphics (with changing graphics in time) Launching applications as a standalone executable file I'm ready to put more effort into it. But I wonder whether I'm burying myself alive trying to implement things which Mathematica isn't devoted to do. I would appreciate links to topics marked with questions signs. How bad is this idea?
What are your opinions? Should I do it in C++? (Doing it in Mathematica would be challenging for me.)
|
As an Eterprise CDF user, I can say I have really tried, and my current opinion is that creating a standalone GUI program with the Wolfram Language is not an easy/commercial/deliverable task at the moment. Here are my points: All the interface controls are very limited. You will have a lot of difficulty to do basic things like make Tab jump between fields, make your interface evaluate when Enter is pressed, or just put form fields in the right positions. For free text fields, export to clipboard or create a pdf/xls/txt
file with your report is possible only with the Enterprise version. To distribute the program you (and anyone who recieves it) have to install Mathematica Player, you can't create a standalone executable. It's strange to use a language that can't be easily delivered. You can't pack your CDF in one file. For big projects, you need to
distribute a folder with a file structure inside it, which is very
clumsy. Normally, when you use Dynamic or something similar, your CDF opens
with a gray screen with a button that have to be unblocked, giving your work
a very unprofessional appearance. You need to see Mathematica advertise ever time you open your Mathematica Player (even in Enterprise edition). You can't hide things like database connections inside your code,
it's very easy to get the string inside java components. For
business applications, you need to refresh data dynamically, and you
can't do this in a secure way. Lack of complete/structured code examples with database connection, nice GUI interface and professional look. You can find some very specific examples like these at wolfram.com, but only very simple toy examples. These are the main reasons I don't recommend CDF for professional standalone applications, in my vision they are good for toy code, students and individual data exploration.
I love Mathematica , but today I have given up developing this kind of application in CDF, maybe Wolfram Language might do something better in the future.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37888",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10834/"
]
}
|
37,936 |
This might be easy, but can't find a way to use DeleteDuplicates to get also list of the actual duplicates. Example: lstA = {1, 2, 4, 4, 6, 7, 8, 8};
r = DeleteDuplicates[lstA]
(* {1, 2, 4, 6, 7, 8} *) I also wanted to get list of the actual duplicates, which are {4,8} in this example.
It would have been nice if DeleteDuplicates would also return those, but there is no option there for that. I do not know what many Mathematica functions do not return back more useful information when called. Many seem to return one piece of information only, and one has to call another function to get another piece of information. For example, here DeleteDuplicates could had an API like this {r,d}=DeleteDuplicates[lst] and r will contain the list after duplicates are moved, but d would contain the actual list of duplicates. To make it even more useful, it can be {r,d,p}=DeleteDuplicates[lst] Where p will be the positions of the duplicates in the original list. Matlab seems to do it this way. Many functions there can return more than one piece of information at a time. This might be due to WL being functional programming language, and designed for cascading function calls, where each function only does one thing at a time. I am not sure now. DeleteDuplicates.html
|
Perhaps one of the simplest ways is to use Tally : p = {1, 2, 4, 4, 6, 7, 8, 8};
Cases[Tally @ p, {x_, n_ /; n > 1} :> x] {4, 8} A somewhat faster formulation: Pick[#, Unitize[#2 - 1], 1] & @@ Transpose[Tally @ p] Taking the optimization to a rather excessive degree: #[[SparseArray[#2, Automatic, 1]["AdjacencyLists"]]] & @@ Transpose[Tally @ p] Though not as fast as the SparseArray optimized form of Tally , an alternative is to use Split after sorting. This is reasonably clean and fast: Flatten[Split @ Sort @ p, {2}][[2]] {4, 8} For Integer data this method is twice as fast as any other listed here: With[{s = Sort @ p},
DeleteDuplicates @
s[[ SparseArray[Unitize @ Differences @ s, Automatic, 1]["AdjacencyLists"] ]]
] Timings p = RandomInteger[1*^8, 1*^6];
Cases[Tally @ p, {x_, n_ /; n > 1} :> x] // Timing // First
Pick[#, Unitize[#2 - 1], 1] & @@ Transpose[Tally @ p] // Timing // First
#[[SparseArray[#2, Automatic, 1]["AdjacencyLists"]]] & @@ Transpose[Tally @ p] //
Timing // First
Flatten[Split @ Sort @ p, {2}][[2]] // Timing // First
With[{s = Sort @ p},
DeleteDuplicates @
s[[ SparseArray[Unitize @ Differences @ s, Automatic, 1]["AdjacencyLists"] ]]
] // Timing // First 0.827
0.343
0.265
0.343
0.11
|
{
"source": [
"https://mathematica.stackexchange.com/questions/37936",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/70/"
]
}
|
38,076 |
I saw a beautiful figure illustrating the optical lattice clock, and would like to make a similar one. This is the figure (taken from here ) Is it possible to make a similar one using Mathematica? Here is my try: Show[
Plot3D[0.05 (Cos[3 x] Cos[
3 y])^4, {x, -\[Pi], \[Pi]}, {y, -\[Pi], \[Pi]},
PlotRange -> {All, All, {-0.1, 0.1}}, PlotPoints -> 200, Mesh -> 60,
MeshStyle -> Gray,
ColorFunction -> (ColorData["GreenPinkTones"][0.5 #3 + 0.5] &)],
Graphics3D[{Darker[Green],
Scale[Sphere[{0, 0, -0.5}],
0.25 {\[Pi]/3, \[Pi]/3, .1}, {0, 0, 0}]}, Lighting -> "Neutral"],
ImageSize -> {651.1743427005708`, 484.8`}, Lighting -> "Neutral",
Method -> {"RotationControl" -> "Globe",
"RotationControl" -> "Globe"},
PlotRange -> {All, All, {-0.1`, 0.1`}},
PlotRangePadding -> {Automatic, Automatic, Automatic},
ViewAngle -> 0.13079882249358044`,
ViewCenter -> {{0.5`, 0.5`, 0.5`}, {0.5218420229698426`,
0.6543497570242808`}},
ViewPoint -> {-2.144844931539977`,
1.84186142553857`, -1.8593511526229505`},
ViewVertical -> {0.`, 0.`, -1.`}]
|
My pc is rather old so there was not much I could do. Maybe no as pretty as in the link but I'm happy because of the result: r = 35;
p = Show[
Plot3D[-Sum[2 Exp[-((x - xo)^2 + (y - yo)^2)], {xo, -24, 8, 4}, {yo, -28, 8, 4}],
{x, -r, r - 4}, {y, -r, r - 4}, Evaluated -> True,
PlotRange -> All, PlotPoints -> 200, Mesh -> 300, ImageSize -> 800,
ColorFunction -> (Blend[{White, White, White, Purple}, -#3] &),
ColorFunctionScaling -> False, MeshStyle -> Directive[Thick, [email protected]]
],
Graphics3D[{Specularity[White, 15], Green, Sphere[{{-4, -4, .2}, {4, 4, .2},
{0, 8, .2}}, 1]}
],
BoxRatios -> Automatic, Boxed -> False, Axes -> False, Lighting -> "Neutral",
ViewVector -> {{10, 20, 11}, {0, 0, 0}}, ViewAngle -> .5];
p = ImageResize[Rasterize[p, "Image", ImageResolution -> 3 72], Scaled[1/3]] manual blurring :) Table[ImageTake[p, {799 - i, 800 - i}, All] ~ Blur ~ (i/100),
{i, 0, 798,2}] // Reverse // Transpose[{#}] & // ImageAssemble I decided to not play with shadows because there is no easy way and my pc nearly died :)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/38076",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1364/"
]
}
|
38,579 |
p1 := y /. {First[Solve[x^2 + y^2 + x == 1, y, Reals]]} {ConditionalExpression[-Sqrt[1 - x - x^2],
1/2 (-1 - Sqrt[5]) < x < 1/2 (-1 + Sqrt[5])]} I want to get the -Sqrt[1 - x - x^2] out of the conditional expression and assign it to a variable. I don't care about the conditions, I'm aware of them and need the expression for use out of the ConditionalExpression . How do I do that? I tried list commands combinations ( Flatten , First , etc.) but they don't work with this. Am I just supposed to copy-paste?
|
You can use Normal , ConditionalExpression is not explicitly mentioned there but documentation says it deals with special forms. p1 = y /. {First[Solve[x^2 + y^2 + x == 1, y, Reals]]} // First ConditionalExpression[-Sqrt[1 - x - x^2], 1/2 (-1 - Sqrt[5]) < x < 1/2 (-1 + Sqrt[5])] Normal @ p1 -Sqrt[1 - x - x^2]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/38579",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10551/"
]
}
|
38,587 |
I know it may sounds idiot, but I've been looking through the document, and couldn't find a way to combine two vectors say {a, b} and {c, d} into {{a, c}, {b, d}} . Thanks all.
|
You are treating $A$ and $B$ as column vectors and combining them column to column, but if you just bracket the two vectors, you are combining them row to row. A final Transpose will do the trick. A = {a, b};
B = {c, d};
NotYourResult = {A,B}
Result = Transpose[{A, B}] where NotYourResult is assigned {{a,b},{c,d}} or
$\left[ {\begin{array}{cc} a & b \\ c & d \\ \end{array} } \right]$, and Result is assigned {{a,c},{b,d}} or
$\left[ {\begin{array}{cc} a & c \\ b & d \\ \end{array} } \right]$,
|
{
"source": [
"https://mathematica.stackexchange.com/questions/38587",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11017/"
]
}
|
38,656 |
I'm trying to plot contours of a function f[x,y,z] on the faces of a cube as the example below, which represents the domain of this function. Is there a way to do it in Mathematica ? The ContourPlot3D evaluates the contours along the domain and I just want them in the faces, colored by the function.
|
Another way using textures: v = {{-1, -1, -1}, {1, -1, -1}, {1, 1, -1}, {-1, 1, -1}, {-1, -1, 1}, {1, -1, 1},
{1, 1, 1}, {-1, 1, 1}};
idx = {{1, 2, 3, 4}, {1, 2, 6, 5}, {2, 3, 7, 6}, {3, 4, 8, 7}, {4, 1, 5, 8}, {5, 6, 7, 8}};
vtc = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
f[{x_, y_, z_}] := x^2 - y^2 - z^2
q[j_] := MapThread[ Prepend, {{Min@#, Max@#} & /@ Transpose@v[[idx[[j]]]], {x, y, z}}]
ranges[i_] := DeleteCases[q[i], {s_, a_, a_}]
anchoredVars[i_] := Cases[q[i], {s_, a_, a_} :> s -> a]
sides = Table[ Rasterize@ ContourPlot[f[{x, y, z}] /. anchoredVars[i],
Evaluate[Sequence @@ ranges[i]], Frame -> False, ColorFunction -> Hue,
ColorFunctionScaling -> False, Method -> {"ShrinkWrap" -> True}], {i, 6}];
Graphics3D[{Black, EdgeForm[None],
Table[{Texture[sides[[i]]],
GraphicsComplex[v, Polygon[idx[[i]], VertexTextureCoordinates -> vtc]]}, {i, 6}]},
Boxed -> False, Method -> {"RotationControl" -> "Globe"}] Edit If you want to use DensityPlot instead of ContourPlot, with PlotPoints->100 you get:
|
{
"source": [
"https://mathematica.stackexchange.com/questions/38656",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11098/"
]
}
|
38,745 |
Bug introduced in version 9.0 and persisting through 10.4 Graphics elements do not always line up perfectly in exported PDFs using "Save As..." method. Take, for example: Graphics[{Point[{0, 1}], Line[{{0, 0}, {0, 1}}]}, AspectRatio -> Automatic] It looks like this on screen: Notice that the dot isn't centred on the end of the line. Now let's export to PDF (hoping that what we saw displayed in the Mathematica GUI is just a rendering problem). Right click the graphic, and choose Save As... -> PDF. The PDF looks like this when magnified in a viewer: There is clearly a very serious misalignment. Is there a workaround? Note: this seems to be a new problem in version 9. Version 7 and 8 are not affected.
|
A simple workaround is to use Export instead of right clicking and choosing Save As ... The result will look like this: Much better. It's not clear to me why this difference exists between saving from the front end or using Export , but there is a significant difference in the quality of the output. Notice that the line widths are different too (the Export version is correct). Conclusion: better not use the interactive Save As feature for graphics, or copy the graphic to the clipboard on OS X (which will have the same rendering imperfections).
|
{
"source": [
"https://mathematica.stackexchange.com/questions/38745",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/12/"
]
}
|
38,851 |
First of all, it appears to me that $$\left|\frac{1}{x} + x^2\right| = \frac{|1 + x^3|}{|x|}$$ is true. I don't know why, but my attempt to verify it in Mathematica failed. In[1]:= Abs[1/x + x^2] === Abs[1 + x^3]/Abs[x]
Out[1]= False It's weird because Mathematica is unable to find a counterexample. In[2]:= FindInstance[Abs[1/x + x^2] != Abs[1 + x^3]/Abs[x], x, Complexes]
Out[2]= {}
|
You are using SameQ which does a direct structural comparison rather than a mathematical one. Since the expressions are not exactly the same it returns False . Try Equal : FullSimplify[Abs[1/x + x^2] == Abs[1 + x^3]/Abs[x]] True FullSimplify is needed for nontrivial comparisons; without it Mathematica will return the equality as given if it is not trivially equivalent. You can also use ForAll and Resolve which I think is sometimes faster (no example at hand): ForAll[x, x != 0, Abs[1/x + x^2] == Abs[1 + x^3]/Abs[x]] // Resolve True
|
{
"source": [
"https://mathematica.stackexchange.com/questions/38851",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11155/"
]
}
|
38,927 |
Please help me to simulate the movement of a particle inside a region with elliptical walls such that particle is reflected from the walls and continues to move. A friend was able write code to simulate a particle represented by a Disk bouncing around inside a square, but we can't do it for an ellipse. x = 0.5;
y = 0.5;
vx = 1;
vy = Pi/2;
step = 0.01;
radius = 0.05;
Animate[
x = x + vx*step;
y = y + vy*step;
If[Abs[x - 1] <= radius || Abs[x] <= radius , vx = -vx];
If[Abs[y - 1] <= radius || Abs[y] <= radius, vy = -vy];
Graphics[{
Cyan, Rectangle[{0, 0}, {1, 1}],
Gray, Disk[{x, y}, radius],
Point[{0.0, 0.0}], Point[{1.0, 1.0}]
}],
{t, 0, Infinity}
]
|
Edit V10! This is simple example what we can now do in real time! R = RegionUnion @@ Table[Disk[{Cos[i], Sin[i]}, .4], {i, 0, 2 Pi, Pi/6.}];
R2 = RegionBoundary@DiscretizeRegion@R;
go[] := (While[r > .105, x += v; r = RegionDistance[R2, x]; Pause[.01]]; bounce[];)
bounce[] := With[{normal = Normalize[x - RegionNearest[R2, x]]},
If[break, Abort[]];
v = .01 Normalize[v - 2 v.normal normal];
x = x + v;
r = RegionDistance[R2, x]; go[]
]
x = {1, 0.};
pos = {x};
break = False;
v = .01 Normalize@{2, 1.};
r = RegionDistance[R2, x];
RegionPlot[R2, Epilog -> Dynamic@Disk[x, .1], AspectRatio -> Automatic]
Button["break at edge", break = True;]
go[] This is an example, not perfect but nice enough to start. V9 Unfortunately I don't have time to explain now. But take a look at wikipedia ellips site, tangent line part especially. DynamicModule[{u = 0, t0, imp, v1, x0 = {0, .49}, v0 = {.5, -1.0}, t, a = 1, b = .5,
c, f1, f2},
DynamicWrapper[
Graphics[{ Thick, Scale[Circle[], {a, b}], AbsolutePointSize@7, Dynamic@Point[x0],
Dashed, Thin, Dynamic@Line[{{x0, imp}, {imp, imp + Normalize@v1},
{imp - normal, imp + normal}}]
}, PlotRange -> 1.1, ImageSize -> 500, Frame -> True],
Refresh[
If[(#/a)^2 + (#2/b)^2 & @@ x0 < 1,
x0 += v0;,
x0 = imp + v1; v0 = v1; rec]
, TrackedSymbols :> {}, UpdateInterval -> .001]]
,
Initialization :> (
c = Sqrt[a^2 - b^2]; v0 = Normalize[v0]/100; f1 = {-c, 0}; f2 = {c, 0};
rec := ({t0, imp} = {t, x0 + t v0
} /. Quiet@NSolve[(#/a)^2 + (#2/b)^2 & @@ (x0 + t v0) == 1. &&
t > 0, t, Reals][[1]];
normal = Normalize[Normalize[imp - f1] + Normalize[imp - f2]];
v1 = Normalize[v0 - 2 normal (v0.normal)]/100;(*bounce*));
rec)]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/38927",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11184/"
]
}
|
39,003 |
I need to apply Van Gogh's stroke brush effect to a random image Take the following image as an example: Thank you so much if you could help!
|
Edit Here is a different approach using Graphics to actually draw some brush strokes. I run a GradientOrientationFilter on a smaller version of the image to estimate the local image gradient, and use that information to create a collection of randomly shaded lines: img = Import["http://i.stack.imgur.com/XwYg7.jpg"];
im = img ~ImageResize~ 200 ~ColorConvert~ "Grayscale";
gof = im ~GradientOrientationFilter~ 5;
lines = MapIndexed[{GrayLevel@RandomReal[],
Line[{#2 - 2 {Cos[#1], Sin[#1]}, #2 + 2 {Cos[#1], Sin[#1]}}]} &,
Reverse /@ Transpose@ImageData@gof, {2}];
brush = Image[
Graphics[lines,
PlotRange -> {{1, #1}, {1, #2}} & @@ ImageDimensions[im],
Background -> GrayLevel[0.5], ImageSize -> ImageDimensions[img]],
ColorSpace -> "Grayscale"]; Here is the brush image: I use a gentle tone-mapping on the original image to equalise the brightness a bit, and then combine the ton-mapped image with the brush strokes. tm = Image`ToneMapHDRI[img, Method -> {"AdaptiveLog", "Bias" -> 1.0}];
Image[0.7 (ImageData@Blur[brush, 2] - 0.6) + ImageData@tm] You can vary the effect by altering parameters such as the scale of the gradient orientation filter and the length of the lines. Original Here's an attempt using tone mapping to equalise the brightness across the image, and a gradient filter to enhance outlines. I added some noise to the image before doing the gradient filter, to try and get some variation in the sky. I found it quite difficult to avoid highlighting the jpeg artefacts in the sky. img = Import["http://i.stack.imgur.com/XwYg7.jpg"];
tm = Image`ToneMapHDRI[img, Method -> {"AdaptiveLog"}];
edges = ColorNegate[
img ~ImageEffect~ {"GaussianNoise", 0.1} ~GradientFilter~ 3] ~ImageAdjust~ {0.2, 0, 5};
ImageMultiply[tm, edges]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39003",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10495/"
]
}
|
39,113 |
I have a matrix $M$ of real components, and I want to split it into two matrices $M^+$ and $M^-$ of the same dimensions as $M$, where $M^+$ contains the positive components of $M$ (the remaining entries being filled with zeros), and $M^-$ contains the negative components, such that $M=M^+ + M^-$. Suppose the matrices are represented in the usual way in Mathematica (as lists of lists, or as sparse arrays) How can I do this efficiently and elegantly in Mathematica?
|
Clip is usually quite fast: m = RandomReal[{-10^6, 10^6}, {3, 3}];
neg = Clip[m, {-Infinity, 0}]
pos = Clip[m, {0, Infinity}] (*{{0., -181286., -442666.}, {0., -233694., -847828.}, {-128249., 0., -540037.}}
{{947792., 0., 0.}, {755278., 0., 0.}, {0., 63058.1, 0.}}*) neg + pos == m True
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39113",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/534/"
]
}
|
39,200 |
In this comment it was asserted that Divide[a,b] and a/b are different, though the documentation indicates that they are the same . In particular, it was asserted that a/b is evaluated as a * 1/b , whereas Divide[a,b] performs the division directly. It was further asserted that this could result in an observable difference in behavior for machine-precision numbers. The question is: is there a difference? If so, what is it exactly? How does it manifest itself? Is there an example where Divide gives a different result than / ? I tried a few edge cases with $MaxMachineNumber and $MinMachineNumber , but didn't find any differences in behavior between the two.
|
Oleksandr is correct about the way evaluation works. a/b seems to be interpreted (parsed) directly as Times[a, Power[b,-1]] , or more readably: $a\times b^{-1}$. Divide[a,b] is interpreted as is. Evaluation then proceeds from these forms, and the arithmetic is carried out differently for the two cases: either $a\times (1/b)$ or $a/b$. Here are some examples that illustrate the evaluation sequence: In[95]:=
On[]
Divide[4,8]
Off[]
During evaluation of In[95]:= On::trace: On[] --> Null. >>
During evaluation of In[95]:= Divide::trace: 4/8 --> 1/2. >>
Out[96]= 1/2
In[98]:=
On[]
4/8
Off[]
During evaluation of In[98]:= On::trace: On[] --> Null. >>
During evaluation of In[98]:= Power::trace: 1/8 --> 1/8. >>
During evaluation of In[98]:= Times::trace: 4/8 --> 4/8. >>
During evaluation of In[98]:= Times::trace: 4/8 --> 1/2. >>
Out[99]= 1/2 This can indeed theoretically lead to different machine precision results. Let's find out if it really does! We are going to compare the complete binary representation of the results, and we won't use == or === (which both have some tolerance). Table[{k, RealDigits[k/137., 2] === RealDigits[Divide[k, 137.], 2]}, {k, 1, 20}]
(* ==> {{1, True}, {2, True}, {3, True}, {4, True}, {5, True}, {6, True}, {7, True},
{8, True}, {9, True}, {10, True}, {11, True}, {12, True}, {13, True},
{14, True}, {15, False}, {16, True}, {17, True}, {18, True}, {19, True}, {20, True}}
*) So Divide[15, 137.] and 15/137. really do lead to different results. Conclusion: yes, there is an observable difference. Again, keep in mind that even === has some tolerance ( Internal`$SameQTolerance ) when comparing machine precision numbers (though less than == , Internal`$EqualTolerance ) and 15/137. === Divide[15, 137.] returns True . The difference is there though as evidenced by the full 53-bit binary representation. So will you ever see the effects of this in practice? Theoretically the error may accumulate, and there are some functions which do not honour these tolerances and perform strict comparisons (try e.g. Union[{15/137., Divide[15, 137.]}] , which returns a list of length 2).
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39200",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/94/"
]
}
|
39,244 |
As an 'user'-level in Mathematica , I mainly use built-in Mathematica function and benefit Mathematica as a mathematical tool-box for my specific scientific problem. My level is not yet programmer-level. The magic of Mathematica is that there are endless level of skill to improve. It is hardly to evaluate a C-programmer by viewing his code. But for Mathematica , be viewing the code, the level could be evaluated. Normally, when skilled level increases, the length of code decreases. Based on the idea of Leonid Shifrin and the level in online game, I myself auto evaluate my skill. Level 0 - Level 20: Beginner-Users who uses mainly built-in functions. Level 20 - Level 40: Intermediate, mix some long procedural programming and functional style Level 40 - Level 60: Expert, low-level system understanding Although I have " Mathematica Advanced Foundation Level" certification, I think my level is Beginner - Pre-Intermediate about level 18- to level 22. I can not understand the Expert level, for example One-Line Code Competition . As we can see here, Expert level codes program in just 'one line'. :) My question is, could you please introduce the use of Mathematica as a real-life application? It is not a question of technique, but a question of idea, imagination. Your applications could open my eye of the use of Mathematica in your real-life. I also see "User Stories" on Wolfram site, but almost of them are scientific, industrial applications. In my case, as an researcher-lecturer at University, I intend to use Mathematica in my teaching. Correct the copies take me a lot of time. So my project is: Use Mathematica to auto generate MCQ (Multiple Choice Question) question based on my question data base. Scan students answers as an image file. Use Mathematica to generate the note by image manipulating on these scanned copies. (The optical reader in my university is really expensive, and not available for everyone). So coding my own Mathematica code is optimal way. Ideas, projects of the use of Mathematica in real life are welcome !
|
This answer is entirely opinion, but given the question, what else could it be? I reject the OP's linear skill rating proposal. Mathematica is too large and to amorphous for the skill of its diverse user community to be categorized in such a tidy way. I also disagree with the OP's view that code will inevitably get more concise as one's Mathematica skills increase. One does get better at playing code golf, but for serious projects -- say writing a Mathematica package intended to be used by many people over many years -- the need to support argument validation, manage options, supply meaningful error and usage messages, support unit and functional-level testing, etc., all conspire to bloat the code far above the conciseness that can be achieved when one doesn't need to worry about such things, such as when answering questions of this site. That is, for many "real-life applications", the need to do software engineering overrides the aesthetics of concise coding.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39244",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1712/"
]
}
|
39,361 |
'Tis the season...
And it's about time I posed my first question on Mathematica Stack Exchange.
So, here's an holiday quest for you Graphics (and P-Chem?) gurus. What is your best code for generating a (random) snowflake in Mathematica?
By random I mean with different shapes that will mimic the diversity exhibited by real snowflakes.
Here's a link to have an idea: http://www.its.caltech.edu/~atomic/snowcrystals/ , more specifically here are the different types of snowflakes: http://www.its.caltech.edu/~atomic/snowcrystals/class/class.htm . Physics-based answers are to be preferred, but graphics only solutions are also welcome.
There already is a thread on generating a snowfall, here: How to create animated snowfall? and one of the posts addresses the problem of generating snowflake-like elements.
In the snowfall post, though, emphasis is on efficient generation of 'snowlike' ensembles . The purpose of this question (apart from having some 'seasonal' fun) is to create graphics that details the structure of a single snowflake. Efficiency is not the primary issue here: beauty is. A very detailed snowflake rendering could even take several minutes of computer power, thus making it unsuitable to incorporate into a snowfall simulation. Here we are trying to generate a single snowflake (possibly with different parameters to tune its shape), the more realistic , the better.
Three dimensional renderings, for adding translucency and colors are also welcome. Unleash your fantasy, go beyond the usual fractals! And if your fantasy is momentarily faltering, as Silvia pointed out in a comment below, on this website http://psoup.math.wisc.edu/Snowfakes.htm you can find a lot of information - and even a C program for the Gravner-Griffeath 2D Snowfake Simulator - on how to generate 'virtual snowflakes', even in 3D (have a look at the pdf files: " Modeling Snow Crystal Growth " I, II and III).
|
I did a very simple (in fact over-simple) snowflake simulator with CellularAutomaton years before. It's based on the hexagonal grid: and range-1 rules: Initial code First we'll need some functions to display our snowflakes: Clear[vertexFunc]
vertexFunc = Compile[{{para, _Real, 1}},
Module[{center, ratio},
center = para[[1 ;; 2]];
ratio = para[[3]];
{Re[#], Im[#]} + {{1, -(1/2)},{0, Sqrt[3]/2}}.Reverse[{-1, 1} center + {3, 0}] & /@
(ratio 1/Sqrt[3] E^(I π/6) E^(I Range[6] π/3))
],
RuntimeAttributes -> {Listable}, Parallelization -> True,
RuntimeOptions -> "Speed"
(*, CompilationTarget->"C"*)];
Clear[displayfunc]
displayfunc[array_, ratio_] := Graphics[{
FaceForm[{ColorData["DeepSeaColors"][3]}],
EdgeForm[{ColorData["DeepSeaColors"][4]}],
Polygon[vertexFunc[Append[#, ratio]] & /@ Position[array, 1]]
}, Background -> ColorData["DeepSeaColors"][0]] Main body Consider 0/1 bistable states for every node on the hexagonal grid, where $0$ stands for empty nodes and $1$ stands for frozen nodes. Then, excluding all-zero case, there are 13 possible arrangements on the 6 vertices of a hexagon(those who are identical under rotation and reflection are considered as the same arrangement): stateSet = Tuples[{0, 1}, 6] // Rest;
gatherTestFunc = Function[lst, Sort[RotateLeft[lst, # - 1] & /@ Flatten[Position[lst, 1]]]];
stateClsSet = Sort /@ Gather[stateSet, gatherTestFunc[#1] == gatherTestFunc[#2] &];
stateClsSetHomogeneous = ArrayPad[#, {{0, 6 - Length@#}, {0, 0}}] & /@ stateClsSet; And the simplest physical rule might be linking different arrangement to different probability of freezing(from $0$ to $1$) or melting(from $1$ to $0$). Those 26 probabilities, pFreeze and pMelt , can be determined by some serious physical models, or can be chosen randomly just for fun. Then they can be used to establish rule function for CellularAutomaton : Clear[ruleFunc2Comp]
ruleFunc2Comp = With[{
stateClsSetHomogeneous = stateClsSetHomogeneous,
seedSet = RandomInteger[{0, 1000}, 1000],
pFreeze = {1, 0.2, 0.1, 0, 0.2, 0.1, 0.1, 0, 0.1, 0.1, 1, 1, 0},
pMelt = {0, 0.7, 0.5, 0.5, 0, 0, 0, 0.3, 0.5, 0, 0.2, 0.1, 0}
},
Compile[{{neighborarry, _Integer, 2}, {step, _Integer}},
Module[{cv, neighborlst, cls, rand},
cv = neighborarry[[2, 2]];
neighborlst = {#[[1, 2]], #[[1, 3]], #[[2, 3]], #[[3, 2]], #[[3, 1]], #[[2, 1]]}&[neighborarry];
If[Total[neighborlst] == 0, cv,
cls = Position[stateClsSetHomogeneous, neighborlst][[1, 1]];
SeedRandom[seedSet[[step + 1]]];
rand = RandomReal[];
Boole@If[cv== 0, rand < pFreeze[[cls]], rand > pMelt[[cls]]]
]
],
RuntimeAttributes -> {Listable}, Parallelization -> True, RuntimeOptions -> "Speed"(*,CompilationTarget -> "C"*)
]
]; Apply ruleFunc2Comp on some initial state for some steps: dataSet = Module[{rule,
initM = {{{0, 0, 0}, {0, 1, 0}, {0, 0, 0}}, 0},
rspec = {1, 1},
tmin = 0, tmax = 50, dt = 1
},
rule = {ruleFunc2Comp, {}, rspec};
CellularAutomaton[rule, initM, {{tmin, tmax, dt}}]
]; You can see how the snowflake grows: Manipulate[
Rotate[displayfunc[dataSet[[k]], .99], 90°],
{k, 1, Length[dataSet], 1}] More snowflakes Some other examples generated with different pFreeze , pMelt and tmax :
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39361",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6745/"
]
}
|
39,445 |
Let's say I'd like to plot Sign[x + 0.5] : Plot[Sign[x + 0.5], {x, -1, 1}] Mathematica will give this: This plot does not show very clearly the value of Sign[x + 0.5] at x = -0.5 : is it 1? is it -1? No, it's 0, but there is no indication of which it is on the plot. This is what I'd like to achieve: (I used Paint to add the markers.) How can I make it Mathematica do it?
|
Update 2015-7-13: PlotPiecewise now handles discontinuities of non- Piecewise functions. (It basically did this before, but required the head to be Piecewise or contain a built-in discontinuous function, like Sign . All I did was brainlessly wrap a function in Piecewise . I also had to rewrite some of the Reduce / PiecewiseExpand code. One of the more complicated examples, which used to expand to a number of integer cases, kept the integer parameter instead of expanding; in another (not shown), the Ceiling of a complicated function was no longer expanded into a Piecewise function. Update: PlotPiecewise now automatically tries to convert a non- Piecewise function into one using PiecewiseExpand . PiecewiseExpand will also do some simplification, such as factoring and reducing a rational function; to avoid that, pass a Piecewise function directly. PlotPiecewise will not alter the formulas in a Piecewise . Note, however, that Mathematica automatically reduces x (x - 1) / (x (x - 2)) but not (x^2 - x) / (x (x - 2)) . A while back I wrote a function PlotPiecewise to produce standard pre-calculus/calculus graphs of Piecewise functions. It works a lot like plot. It evolved from time to time, but it's nowhere near a complete package. For instance, PlotPiecewise is not HoldAll like Plot , because it was convenient for a certain use-case and my typical uses didn't need it either. There are a few options, but not really a complete set. Another limitation is that it was intended for rather simple piecewise functions, of the type one might ask students to graph by hand. For instance, it uses Reduce and Limit to find asymptotes but doesn't check if they worked; one should really check. It won't handle functions that are too complicated or that cannot be expanded as Piecewise functions. I'll offer it, since it seems to do what the OP asks and I've already written. It seems worth sharing. I hope the community appreciates it. Code dump at the end. OP's example *Update: There is no longer a need to expand Sign . PlotPiecewise will automatically do it.** PlotPiecewise[Sign[x + 1/2], {x, -1, 1}] More Examples PlotPiecewise[
Piecewise[{
{ 1 / (-1 + 2 x), 0 < x <= 1},
{ 2, x == 0},
{ -x, x < 0},
{ (2 - x) / (-3 + x), 1 < x < 4},
{ -6 + x, 4 < x}},
Indeterminate],
{x, -2, 6.5},
AspectRatio -> Automatic, PlotRange -> {-2.8, 3.1},
Ticks -> {Range[-3, 6], Range[-4, 3]}] g[t_] := Piecewise[{
{Abs[1 + t], -2 <= t < 0},
{2, t == 0},
{2 - Cos[Pi*t], 0 < t < 2},
{(-16 - 12*t + t^3)/(8*(-4 + t)), t >= 2}},
Indeterminate];
PlotPiecewise[g[t], {t, -2, 6}, PlotRange -> {-2, 9}, DotSize -> Offset[{3, 3}]] Update: New cases handled The updated code can do these things: PlotPiecewise[Exp[(Sign[Sin[x^2]] - 3/4) x/2] - 1, {x, 0, 10}] PlotPiecewise[
Piecewise[{
{(-1 + 3*x)^(-1), -1 < x <= 1},
{Tan[Pi*x], 1 < x < 11/2}},
Indeterminate],
{x, -2, 6.5}, AspectRatio -> Automatic, PlotRange -> {-2.8, 3.1},
Ticks -> {Range[-3, 6], Range[-4, 3]}] New examples (2015-7-13) From Is there any way to reveal a removable singularity in a plot? : PlotPiecewise[(2^x - 2)/(x - 1), {x, -2, 2},
"DotSize" -> Offset[{3, 3}],
"EmptyDotStyle" ->
EdgeForm[Directive[ColorData[97, 1], AbsoluteThickness[1.6]]]] A similar one: PlotPiecewise[(2^x - 2)/(x^2 - 1), {x, -2, 2}] Code dump Here is an update. It is I hope written in a somewhat better style. I also took the opportunity to add a couple of features. PlotPiecewise will automatically apply PiecewiseExpand , and if it produces a Piecewise function it will plot it. It will also handle a wider range of conditions in a Piecewise function. There is a bit more error checking, and some error messages have been added. It is still not HoldAll . Since Mr.Wizard prodded me to improve the code, I tried to keep it so that it would work in V7. ClearAll[PlotPiecewise, PlotPiecewise`plot, PlotPiecewise`init,
PlotPiecewise`solve, PlotPiecewise`expand,
PlotPiecewise`annotatedPoints, PlotPiecewise`boundaryPoints,
PlotPiecewise`interiorPoints, PlotPiecewise`sowAnnotations,
PlotPiecewise`inDomain];
PlotPiecewise::usage =
"PlotPiecewise[Piecewise[...], {x, a, b}, opts]";
PlotPiecewise::limindet =
"Limit `` is not numeric or infinite at ``";
PlotPiecewise::nonpw =
"Function `` is not a Piecewise function or did not expand to one";
PlotPiecewise`debug::debug = "``";
PlotPiecewise`debug::plot = "``";
PlotPiecewise`debug::annotation = "``";
PlotPiecewise`debug::limit = "``";
PlotPiecewise`debug =
Hold[PlotPiecewise`debug::debug, PlotPiecewise`debug::plot,
PlotPiecewise`debug::annotation, PlotPiecewise`debug::limit];
Off @@ PlotPiecewise`debug;
Options[PlotPiecewise] =
Join[{"DotSize" -> Automatic, "EmptyDotStyle" -> Automatic,
"FilledDotStyle" -> Automatic, "AsymptoteStyle" -> Automatic,
"BaseDotSize" -> Offset[{2, 2}],
"AdditionalPoints" -> {}, (*
addition pts to annotate *)
"PiecewiseExpand" -> Automatic, (* which fns.
to expand *)
"ContinuousEndpoints" -> Automatic},(* eval.
formula, not limit *)
Options[Plot]];
Options[EmptyDot] = Options[FilledDot] = Options[Asymptote] =
Options[PlotPiecewise`plot] = Options[PlotPiecewise`init] =
Options[PlotPiecewise];
(* graphics elements *)
Clear[EmptyDot, FilledDot, Asymptote];
EmptyDot[pt_, opts : OptionsPattern[]] /;
OptionValue["EmptyDotStyle"] === None := {};
FilledDot[pt_, opts : OptionsPattern[]] /;
OptionValue["FilledDotStyle"] === None := {};
Asymptote[pt_, opts : OptionsPattern[]] /;
OptionValue["AsymptoteStyle"] === None := {};
EmptyDot[pt_, opts : OptionsPattern[]] := {White,
OptionValue["EmptyDotStyle"] /. Automatic -> {},
Disk[pt,
OptionValue["DotSize"] /.
Automatic -> OptionValue["BaseDotSize"]]};
FilledDot[pt_,
opts : OptionsPattern[]] := {OptionValue["FilledDotStyle"] /.
Automatic -> {},
Disk[pt,
OptionValue["DotSize"] /.
Automatic -> OptionValue["BaseDotSize"]]};
Asymptote[x0_, opts : OptionsPattern[]] := {Dashing[Large],
OptionValue["AsymptoteStyle"] /. Automatic -> {},
Line[Thread[{x0, OptionValue[PlotRange][[2]]}]]};
PlotPiecewise`$inequality =
Greater | Less | LessEqual | GreaterEqual;
PlotPiecewise`$discontinuousAuto = Ceiling | Floor | Round | Sign;
PlotPiecewise`$discontinuousAll =
Ceiling | Floor | Round | Sign |(*Min|Max|Clip|*)UnitStep |
IntegerPart |(*FractionalPart|*)Mod | Quotient | UnitBox |
UnitTriangle |
SquareWave(*|TriangleWave|SawtoothWave*)(*|BernsteinBasis|\
BSplineBasis|Abs|If|Which|Switch*);
PlotPiecewise`$discontinuous = Ceiling | Floor | Round | Sign;
(* auxiliary functions*)
(* causes Conditional solutions to expand to all possibilities;
(arises from trig eq, and C[1] -- perhaps C[2], etc?
*)
PlotPiecewise`expand[cond_Or, var_] :=
PlotPiecewise`expand[#, var] & /@ cond;
PlotPiecewise`expand[cond_, var_] :=
Reduce[cond, var, Backsubstitution -> True];
PlotPiecewise`solve[eq_, var_] /;
MemberQ[eq, PlotPiecewise`$discontinuous, Infinity,
Heads -> True] :=
PlotPiecewise`solve[# == C[1] && C[1] ∈ Integers &&
And @@ Cases[eq, Except[_Equal]], var] & /@
Cases[eq, PlotPiecewise`$discontinuous[e_] :> e, Infinity];
PlotPiecewise`solve[eq_,
var_] := {var -> (var /. #)} & /@
List@ToRules@
PlotPiecewise`expand[
Reduce[eq, var, Reals, Backsubstitution -> True],
var] /. {False -> {}};
(* limit routines for handling discontinuous functions,
which Limit fails to do *)
Needs["NumericalCalculus`"];
PlotPiecewise`nlimit[f_?NumericQ, var_ -> x0_, dir_] := f;
PlotPiecewise`nlimit[f_, var_ -> x0_, dir_] :=
NLimit[f, var -> x0, dir];
PlotPiecewise`limit[f_, var_ -> x0_, dir_] /;
MemberQ[Numerator[f], PlotPiecewise`$discontinuous, Infinity,
Heads -> True] :=
Module[{y0, f0},
f0 = f //. (disc : PlotPiecewise`$discontinuous)[z_] /;
FreeQ[z, PlotPiecewise`$discontinuous] :> disc[
With[{dz = Abs[D[z, var] /. var -> N@x0]},
Mean[{z /. var -> N@x0,
z /. var -> x0 - 0.1 Last[dir]/Max[1, dz]}]]
];
Message[PlotPiecewise`debug::limit, {f0, f, var -> x0, dir}];
Quiet[Check[y0 = PlotPiecewise`nlimit[f0, var -> x0, dir],
Check[y0 = Limit[f0, var -> x0, dir],
If[! NumericQ[y0], y0 = Indeterminate]]], {Power::infy,
Infinity::indet, NLimit::noise}];
y0
];
PlotPiecewise`limit[f_, var_ -> x0_, dir_] :=
Module[{y0},
Quiet[Check[y0 = f /. var -> x0,
Check[y0 = Limit[f, var -> x0, dir],
If[! NumericQ[y0], y0 = Indeterminate]]], {Power::infy,
Infinity::indet}];
y0
];
PlotPiecewise`$reverseIneq = {Less -> Greater, Greater -> Less,
LessEqual -> GreaterEqual};
PlotPiecewise`reverseIneq[(rel : PlotPiecewise`$inequality)[
args__]] := (rel /. PlotPiecewise`$reverseIneq) @@
Reverse@{args};
PlotPiecewise`inDomain[] :=
LessEqual @@ PlotPiecewise`domain[[{2, 1, 3}]];
PlotPiecewise`inDomain[dom_] := LessEqual @@ dom[[{2, 1, 3}]];
(* annotatedPoints --
returns list of abscissas to be "annotated"
with dots/asymptotes
boundaryPoints --
returns list of boundaries numbers between \
pieces
interiorPoints --
returns list of points where the \
denominator is zero
*)
PlotPiecewise`annotatedPoints[allpieces_, domain_,
additionalpoints_] :=
DeleteDuplicates@Flatten@Join[
PlotPiecewise`boundaryPoints[allpieces, domain],
PlotPiecewise`interiorPoints[allpieces, domain],
additionalpoints
];
PlotPiecewise`boundaryPoints[allpieces_, domain : {var_, _, _}] :=
With[{conditions =
DeleteDuplicates[
Equal @@@
Flatten[Last /@
allpieces /.
{HoldPattern@
Inequality[a_, rel1_, b_, rel2_,
c_] :> {PlotPiecewise`reverseIneq[rel1[a, b]],
rel2[b, c]}, (rel : PlotPiecewise`$inequality)[a_, b_,
c_] :> {PlotPiecewise`reverseIneq[rel[a, b]], rel[b, c]}}
]]},
Message[PlotPiecewise`debug::annotation, conditions];
var /.
Flatten[ (* deletes no soln {}'s *)
PlotPiecewise`solve[# && PlotPiecewise`inDomain[domain],
var] & /@ conditions,
1] /. var -> {} (* no BPs in domain *)
];
PlotPiecewise`interiorPoints[allpieces_, domain : {var_, _, _}] :=
MapThread[
Function[{formula, condition},
Flatten[
{With[{solns =
PlotPiecewise`solve[
Denominator[formula, Trig -> True] ==
0 && (condition /. {LessEqual -> Less,
GreaterEqual -> Greater}) &&
LessEqual @@ PlotPiecewise`domain[[{2, 1, 3}]],
PlotPiecewise`var]},
PlotPiecewise`var /. solns /. PlotPiecewise`var -> {}
],
If[MemberQ[Numerator[formula], PlotPiecewise`$discontinuous,
Infinity, Heads -> True],
With[{solns =
PlotPiecewise`solve[
Numerator[formula] ==
0 && (condition /. {LessEqual -> Less,
GreaterEqual -> Greater}) &&
LessEqual @@ PlotPiecewise`domain[[{2, 1, 3}]],
PlotPiecewise`var]},
PlotPiecewise`var /. solns /. PlotPiecewise`var -> {}
],
{}
]}
]],
Transpose@allpieces
];
(* sowAnnotations - Sows irregular points, tagged with three ids;
"filled" \[Rule] {x,y};
"empty" \[Rule] {x,y};
"asymptote" \[Rule] x;
*)
PlotPiecewise`sowAnnotations[allpieces_,
domain : {var_, a_, b_}, {}] := {};
PlotPiecewise`sowAnnotations[allpieces_, domain : {var_, a_, b_},
points_List] :=
(Message[PlotPiecewise`debug::annotation,
"sowAnn" -> {allpieces, points}];
PlotPiecewise`sowAnnotations[allpieces, domain, ##] & @@@
Partition[{If[First[#] == a, Indeterminate, a]}~Join~#~
Join~{If[Last[#] == b, Indeterminate, b]}, 3, 1] &@
SortBy[points, N]);
PlotPiecewise`sowAnnotations[allpieces_, domain : {var_, _, _},
xminus_, x0_?NumericQ, xplus_] :=
Module[{y0, yplus, yminus, f0, fminus, fplus},
f0 = First[
Pick @@ MapAt[# /. var -> x0 & /@ # &, Transpose@allpieces,
2] /. {} -> {Indeterminate}];
Quiet[y0 = f0 /. var -> N@x0, {Power::infy, Infinity::indet}];
If[xminus =!= Indeterminate, (* xminus ≠ left endpoint *)
fminus =
First[Pick @@
MapAt[# /. var -> Mean[{xminus, x0}] & /@ # &,
Transpose@allpieces, 2] /. {} -> {Indeterminate}];
yminus = PlotPiecewise`limit[fminus, var -> x0, Direction -> 1];
];
If[xplus =!= Indeterminate, (* xplus ≠ right endpoint *)
fplus = First[
Pick @@ MapAt[# /. var -> Mean[{x0, xplus}] & /@ # &,
Transpose@allpieces, 2] /. {} -> {Indeterminate}];
yplus = PlotPiecewise`limit[fplus, var -> x0, Direction -> -1];
];
If[Abs[yminus] == Infinity || Abs[yplus] == Infinity,
Sow[x0, "asymptote"]];
If[NumericQ[y0],
Sow[{x0, y0}, "filled"]];
Message[
PlotPiecewise`debug::annotation, {{x0, y0, f0}, {xminus, yminus,
fminus}, {xplus, yplus, fplus}}];
Sow[{x0, #}, "empty"] & /@
DeleteDuplicates@DeleteCases[Select[{yminus, yplus}, NumericQ], y0]
];
(* initialization of context variables *)
PlotPiecewise`init[f : HoldPattern@Piecewise[pieces_, default_],
domain : {var_, _, _},
opts : OptionsPattern[]] :=
(PlotPiecewise`domain =
SetPrecision[domain, Infinity];
PlotPiecewise`var = var;
PlotPiecewise`allpieces =
If[default =!= Indeterminate,
Append[pieces,(*
add True case to pieces *)
{default,
If[Head[#] === Not, Reduce[#], #] &@
Simplify[Not[Or @@ (Last /@ pieces)]]}],
pieces] /. {formula_, HoldPattern@Or[e__]} :>
Sequence @@ ({formula, #} & /@ List[e]);
PlotPiecewise`$discontinuous =
OptionValue[
"PiecewiseExpand"] /. {Automatic ->
PlotPiecewise`$discontinuousAuto,
All -> PlotPiecewise`$discontinuousAll, None -> {}};
Message[PlotPiecewise`debug::debug, "f" -> f]
);
(* The main plotting function *)
PlotPiecewise`plot[f : HoldPattern@Piecewise[pieces_, default_],
domain : {var_, a_, b_}, opts : OptionsPattern[]] :=
Block[{PlotPiecewise`var, PlotPiecewise`domain,
PlotPiecewise`allpieces, PlotPiecewise`$discontinuous},
(* INITIALIZATION:
PlotPiecewise`var;
PlotPiecewise`domain;
PlotPiecewise`allpieces;
PlotPiecewise`$discontinuous
*)
PlotPiecewise`init[f, domain, opts];
Message[PlotPiecewise`debug::plot,
"allpieces" -> PlotPiecewise`allpieces];
(* POINTS OF INTEREST *)
With[{annotatedpoints = PlotPiecewise`annotatedPoints[
PlotPiecewise`allpieces,
PlotPiecewise`domain,
OptionValue["AdditionalPoints"]],
plotopts =
FilterRules[{opts},
Cases[Options[Plot], Except[Exclusions -> _]]]},
Message[PlotPiecewise`debug::plot,
"annotatedpoints" -> annotatedpoints];
(* ANNOTATIONS *)
With[{annotations = Last@Reap[
PlotPiecewise`sowAnnotations[
PlotPiecewise`allpieces,
PlotPiecewise`domain,
annotatedpoints],
{"asymptote", "empty", "filled"}]},
Message[PlotPiecewise`debug::plot,
Thread[{"asymptote", "empty", "filled"} -> annotations]];
(* PROCESS PLOT *)
With[{exclusions = Join[
If[OptionValue[Exclusions] === None, {},
Flatten[{OptionValue[Exclusions]}]],
PlotPiecewise`var == # & /@
Flatten[First@annotations]](*can't we use annotatedpoints?*)},
With[{curves =
Plot[f, domain,
Evaluate@Join[{Exclusions -> exclusions}, plotopts]]},
Show[curves,
Graphics[{ColorData[1][1], EdgeForm[ColorData[1][1]],
OptionValue[PlotStyle] /. Automatic -> {},
MapThread[
Map, {{Asymptote[#, PlotRange -> PlotRange[curves],
opts] &, EmptyDot[#, opts] &, FilledDot[#, opts] &},
If[Depth[#] > 2, First[#], #] & /@ annotations}]}]]]]
]]
];
(* The user-interface *)
PlotPiecewise[f : HoldPattern@Piecewise[pieces_, default_], domain_,
opts : OptionsPattern[]] := PlotPiecewise`plot[f, domain, opts];
(* tries to expand f as a Piecewise function *)
PlotPiecewise`pweMethods = {"Simplification" -> False,
"EliminateConditions" -> False, "RefineConditions" -> False,
"ValueSimplifier" -> None};
PlotPiecewise[f_, domain : {var_, a_, b_}, opts : OptionsPattern[]] :=
Block[{PlotPiecewise`graphics},
(* restrict var in PiecewiseExpand/Reduce*)
With[{a0 = If[# < a, #, # - 1/2] &@Floor[a],
b0 = If[# > b, #, # + 1/2] &@Ceiling[b]},
With[{pwf =
Assuming[a0 < var < b0,
PiecewiseExpand[
f /. dis : PlotPiecewise`$discontinuousAll[_] :> Piecewise[
Map[
{#[[1, -1]],
Replace[#[[2 ;;]], cond_ /; ! FreeQ[cond, C[_]] :>
(Reduce[#, var,
DeleteDuplicates@Cases[#, C[_], Infinity]] & /@
LogicalExpand[
cond /.
HoldPattern[And[e__?(FreeQ[#, var] &)]] :>
Reduce[And[e]]])
]} &,
List @@
Reduce[dis == C[1] && C[1] ∈ Integers &&
a0 < var < b0, {C[1], x}, Backsubstitution -> True]],
Indeterminate], Method -> PlotPiecewise`pweMethods]]},
If[Head[pwf] === Piecewise,
PlotPiecewise`graphics = PlotPiecewise`plot[pwf, domain, opts],
PlotPiecewise`graphics =
PlotPiecewise`plot[
Piecewise[{{f, -Infinity < var < Infinity}}, Indeterminate],
domain, opts]]
]];
PlotPiecewise`graphics
];
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39445",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11426/"
]
}
|
39,476 |
Fold is an extension of Nest for 2 arguments. How does one extend this concept to multiple arguments. Here is a trivial example: FoldList[#1 (1 + #2) &, 1000, {.01, .02, .03}] Say I want do something like: FoldList[#1(1+#2)-#3&,1000,{.01,.02,.03},{100,200,300}] where 100,200,300 are the values for #3. I know Fold doesn't work this way. I'm looking for an approach that will work like this... ((1000*(1.01)-100)*1.02-200)*1.03-300). Is there a way to extend Fold to more than 2 arguments? or is there a better approach for solving problems like this?
|
Yes, there is. Group your extra arguments in a list, and address them by their positions in the function under Fold . For your particular example: FoldList[#1 (1 + First@#2) - Last@#2 &, 1000, Transpose@{{.01, .02, .03}, {100, 200, 300}}]
(* {1000, 910., 728.2, 450.046} *)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39476",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11282/"
]
}
|
39,879 |
I am new to Mathematica , and I'm looking for a way to create patterns on the surface of 3D objects. One thing I have not been able to do is to create a hexagonal mesh on a torus. What I would like to have is a hexagonal mesh that has a certain thickness (so that it would be 3D-printable). So far, I have been able to create the torus itself. I am not sure of how to create the hexagonal pattern on the surface, and the process of mapping it onto the torus. ParametricPlot3D[{Cos[t] (3 + Cos[u]), Sin[t] (3 + Cos[u]), Sin[u]},
{t, 0, 2 Pi}, {u, 0, 2 Pi}]
|
We can do this by building a regular hexagon tile and wrapping it onto a torus: hexTile[n_, m_] :=
With[{hex = Polygon[Table[{Cos[2 Pi k/6] + #, Sin[2 Pi k/6] + #2}, {k, 6}]] &},
Table[hex[3 i + 3 ((-1)^j + 1)/4, Sqrt[3]/2 j], {i, n}, {j, m}] /.
{x_?NumericQ, y_?NumericQ} :> 2 π {x/(3 m), 2 y/(n Sqrt[3])}
]
ht = With[{torus = {Cos[#] (3 + Cos[#2]), Sin[#] (3 + Cos[#2]), Sin[#2]} &},
Graphics3D[hexTile[20, 20] /. Polygon[l_List] :> Polygon[torus @@@ l], Boxed -> False]
] You can now convert this to a wire frame by changing the polygons to lines or tubes, whichever is convenient for you: ht /. Polygon[x__] :> {Thick, Line@x} ht /. Polygon -> Tube
|
{
"source": [
"https://mathematica.stackexchange.com/questions/39879",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11590/"
]
}
|
40,314 |
I entered a command incorrectly as follows: DSolve[{y'[x]=y[x]},y[x],x] I am now experiencing: DSolve[{y'[x] == y[x]}, y[x], x] During evaluation of In[26]:= DSolve::deqn: Equation or list of equations expected instead of True in the first argument {True}. >> (* DSolve[{True},y(x),x] *) How do I recover from this error. I've tried Clear[y'[x]] . That didn't work.
|
It is for situations like this that Unset exists. :-) After the mistaken Set operation: y'[x] = "oh dear";
y'[x] "oh dear" Merely use: y'[x] =. The definition is cleared: y'[x] y'[x] Please see halirutan's answer for an explanation of why ClearAll[y] does not work here.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/40314",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5183/"
]
}
|
40,334 |
EDIT: (my conclusion and thank you note) I want to thank you all guys for this unexpected intellectual and artistic journey. Hope you had fun and enjoyed it the same as I did. I would like to generate a circle pack that mimics this: (don't pay attention on numbers, and colors at all, at the moment I am interested in circle positions and radii only) or this: I am new in Mathematica, could you give me some guidance? Thnx. EDIT: The question was strictly for planar case (and remains so), however I see @Jacob Akkerboom in his answer added a solution for 3D generalization (thanks!), and, speaking of that, I just want here to bring to your attention this picture: EDIT 2: There are some applications of circle packing in irregular shapes, like this: (author Jerome St Claire, handpainted) ... and a font called Dotted: (author Maggie Janssen) ... and some logos: ... garden design: ... infographics: ... and these hypnotic images: (from percolatorapp )
|
replacing RandomReal function in István's code with u = RandomVariate[UniformDistribution[{0,1 - ((1 - 2 min)/(max - min) (r - min) + 2 min)}]] leads to non-uniform distribution Randomization for the angle can also be non-uniform: randomPoint =
Compile[{{r, _Real}},
Module[{u =
RandomVariate[
UniformDistribution[{0,
1 - (-((1 - 2 min)/(max - min)) (r - min) + 1)}]],
a = RandomVariate[
UniformDistribution[{π/(max - min)^(1/10) (r - min)^(1/10),
2 π - π/(max - min)^(1/10) (r - min)^(
1/10)}]]}, {Sqrt@u*Cos[a 2 Pi], Sqrt@u*Sin[a 2 Pi]}],
Parallelization -> True, CompilationTarget -> "C",
RuntimeOptions -> "Speed"]; The same applies to color. I think that after playing for long enough with these distributions you may even get some beautiful shapes. The real challenge would be to build new compilable distributions based on some graphics, like the figures in your example, or even some edge-detected pictures. Edit (thanks to Simon Woods).
The same idea may be implemented much easier using Simon's approach. We just have to make the radius choice dependent on the distance to the border. Inside the main loop replace the definition of r : r = Min[max, d, m Exp[-(d/m)^0.2]] This way the code respects fine details of the shape. You can see the the elephant's tail is drawn in small circles, which is common sense. And it takes about 40 seconds to render all the zigs and zags of Norway's shoreline (set imagesize to 500, max=10 , min=0.5 , pad=0.2 ). Further, changing Simon's definition of m by adding a background value we can create distinguishable shapes in a pool of small circles: distance =
Compile[{{pt, _Real, 1}, {centers, _Real, 2}, {radii, _Real, 1}},
(Sqrt[Abs[First@# - First@pt]^2 + Abs[Last@# - Last@pt]^2] & /@ centers) - radii,
Parallelization -> True, CompilationTarget -> "C", RuntimeOptions -> "Speed"];
max = 20;(*largest disk radius*)
min = 0.5;(*smallest disk radius *)
pad = 1;(*padding between disks*)
color = ColorData["DeepSeaColors"];
timeconstraint = 10;
shape = Binarize@ColorNegate@ImageCrop@Rasterize@Style["A", FontSize -> 1000];
centers = radii = {};
Module[{dim, dt, pt, m, d, r},
dim = ImageDimensions[shape];
dt = DistanceTransform[shape];
TimeConstrained[While[True,
While[
While[
pt = RandomReal[{1, #}] & /@ dim;
(m = 3 + ImageValue[dt, pt]) < min];
(d = Min[distance[pt, centers, radii]] - pad) < min];
r = Min[max, d, m];
centers = Join[centers, {pt}];
radii = Join[radii, {r}]
], timeconstraint]]
Graphics[{color@RandomReal[], #} & /@ MapThread[Disk, {centers, radii}]] And after that we can finally get to coloring (again, this is a modification of Simon's code): distance = Compile[{{pt, _Real, 1}, {centers, _Real, 2}, {radii, _Real,1}}, (Sqrt[Abs[First@# - First@pt]^2 + Abs[Last@# - Last@pt]^2] & /@centers) - radii, Parallelization -> True, CompilationTarget -> "C", RuntimeOptions -> "Speed"];
max = 8;(*largest disk radius*)
min = 2;(*smallest disk radius*)
pad = 1.5;(*padding between disks*)
color1 = ColorData["Aquamarine"];
color2 = ColorData["SunsetColors"];
timeconstraint = 10;
background = 7;
shape = Binarize@ColorNegate@Rasterize@Style["74", Bold, Italic, FontFamily -> "PT Serif", FontSize -> 250];
centers = radii = colors = {};
Module[{dim, dt, pt, m, d, r}, dim = ImageDimensions[shape];
dt = DistanceTransform[shape];
TimeConstrained[
While[True, While[While[pt = RandomReal[{1, #}] & /@ (2 dim);
(m = If[Norm[pt - dim] < 200, background, 0] + If[pt[[1]] < dim[[1]] 3/2 && pt[[1]] > dim[[1]]/2 && pt[[2]] < dim[[2]] 3/2 && pt[[2]] > dim[[2]]/2, ImageValue[dt, pt - dim/2], 0]) < min];
(d = Min[distance[pt, centers, radii]] - pad) < min];
r = Min[max, d, m ];
centers = Join[centers, {pt}];
radii = Join[radii, {r}];
colors =Join[colors, {Blend[{color2@RandomReal[{0.4, 0.7}], color1@RandomReal[{0.4, 0.7}]}, Piecewise[{{1/max*(m - background), m < background + max/2}, {1, m >= background + max/2}}]]}]];, timeconstraint]]
Graphics[MapThread[{#1, Disk[#2, #3]} &, {colors, centers, radii}]]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/40334",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11710/"
]
}
|
40,526 |
How can I construct a moving maximum function? For example, if I have a list of 12 values: { 5, 6, 9, 3, 2, 6, 7, 8, 1, 1, 4, 7 } and I want to maximize over 3 values then the expected result would be: { 6, 9, 9, 9, 6, 7, 8, 8, 8, 4, 7, 7 } .
|
test = {5, 6, 9, 3, 2, 6, 7, 8, 1, 1, 4, 7}
MaxFilter[test, 1]
(* {6, 9, 9, 9, 6, 7, 8, 8, 8, 4, 7, 7} *) You can also use Max /@ Transpose[{Rest[Append[#, 0]], #, Most[Prepend[#, 0]]}] &[yourList] which is competitive with the MM MaxFilter, but will allow you to change the 'slide' (e.g.pad with zeroes, or other arbitrary 'start').
|
{
"source": [
"https://mathematica.stackexchange.com/questions/40526",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10067/"
]
}
|
40,533 |
Why does the following code produce different result? In my mental model, they should be the same. Table[With[{x = i^k}, HoldForm[x]], {k, 1, 5}]
With[{x = i^k}, HoldForm[x]] // Table[#, {k, 1, 5}] & Output: {i,i^2,i^3,i^4,i^5}
{i^k,i^k,i^k,i^k,i^k}
|
test = {5, 6, 9, 3, 2, 6, 7, 8, 1, 1, 4, 7}
MaxFilter[test, 1]
(* {6, 9, 9, 9, 6, 7, 8, 8, 8, 4, 7, 7} *) You can also use Max /@ Transpose[{Rest[Append[#, 0]], #, Most[Prepend[#, 0]]}] &[yourList] which is competitive with the MM MaxFilter, but will allow you to change the 'slide' (e.g.pad with zeroes, or other arbitrary 'start').
|
{
"source": [
"https://mathematica.stackexchange.com/questions/40533",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1643/"
]
}
|
40,731 |
I am very new to mathematica but it looks like an interesting language and I would like to explore it for a future project to create a web search engine. It seems like it would be fairly well suited for this as it seems to already be powering wolfram alpha. I was wondering if the only databases you can hook into are SQL like databases. I can't see anywhere that talks about hooking into Mongo or a graph database like Neo4j. Why is this? Does this not make sense for some reason? Any thoughts would be great. Thanks. Edit: So ya. If you have examples of ways to connect Mathematica to MongoDB that would be awesome. If possible I would also like to see an example of connecting it to Neo4j. (Or reasons why that would not make sense). I guess I am wondering why everything for Mathematica is being used to connect to SQL databases thus far? Is there a reason for that?
|
Here are the two ways I have successfully used MongoDB with Mathematica. AFAIK much of this would also apply to similar DBs such as CouchDB. A. Easy way One working example used a third party Mongo supplier such as 28msec.io and use URLFetch e.g. With this supplier you can both read from and write to the database using HTTP GET and simple query strings. While I have not tested it, it seems to me that you should be able to make calls to a set up such as this from a free CDF (it is my understanding that you can import from a URL from free CDF). B. Stand alone implementation I have installed MongoDB on my Mac and got it working with Mathematica using this method: I do not imagine that the set up would be too different on other systems. To interface with Mathematica I have used the REST API. For me as a non-Java programmer this was far more straight forward than trying to make a JLink connector. I have no idea of performance issues of the REST API vs purpose built JLink connector. For the intended application there were no noticeable problems, slowdowns etc. 1 Download and install MongoDB. 2 Start the webserver $ sudo apachectl start 3 Start Mongo DB $ mongod --rest 4 Check that everything is working on port 28017 127.0.0.1:28017 The problem with the install is that the bundled REST interface does not allow inserting etc. Full REST capabilities can be achieved with an external tool such as sleepy mongoose . 5 Install pymongo $ easy_install pymongo 6 Download and install sleepy.mongoose . You are now in business and can read from and write to your local MongoDB from Mathematica using URLFetch . Edit Forgot to mention that you use ImportString[ string, "JSON"] to convert the JSON to rules. Also forgot to mention that for easy option A, or similar database providers, if you can enter the login and password as part of the query string then you can use Import to read from, and write to, the database. Edit 2 I've been using RESTHeart for the past few months and find that a better API. Add your instructions using the "Body" option for URLFetch .
|
{
"source": [
"https://mathematica.stackexchange.com/questions/40731",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11853/"
]
}
|
41,013 |
With the command ListPlot[data,Joined -> True] I can visually connect adjacent data points in the array with lines. However, this option appears to be missing in ListPointPlot3D ? Is there some manner with which to join with to join (with a line) adjacent three-dimensional points? There will be a large number of points in my data structure, and I'd really like to keep the standard output format of ListPointPlot3D .
|
pts = RandomReal[{0, 1}, {19, 3}];
Show[ListPointPlot3D@pts, Graphics3D@Line@pts] Edit: Something slightly more useful as an example: data = RandomFunction[RandomWalkProcess[0.3], {0, 10^2}, 3];
pts = Transpose@data["States"];
Show[ListPointPlot3D@#, Graphics3D@Line@#] &@pts
|
{
"source": [
"https://mathematica.stackexchange.com/questions/41013",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11894/"
]
}
|
41,614 |
I want to do the following: I have two lists {a_1,...a_n}, {b_1,...,b_n} and I would like to build now all shuffles out of this. This means all unions of these lists while still keeping the individual order of the parent lists. Example {a,b}, {c,d} {{c,d,a,b},{c,a,d,b},{c,a,b,d},{a,c,d,b},{a,c,b,d},{a,b,c,d}} Is there any easy way to do this?
|
Recursion This is top-level code and therefore unlikely to be as efficient as a compiled solution, but the recursive algorithm should have reasonable computational complexity: f[u : {a_, x___}, v : {b_, y___}, c___] := f[{x}, v, c, a] ~Join~ f[u, {y}, c, b]
f[{x___}, {y___}, c___] := {{c, x, y}} (* rule for empty-set termination *) Now: f[{a, b}, {c, d}] {{a, b, c, d}, {a, c, b, d}, {a, c, d, b}, {c, a, b, d}, {c, a, d, b}, {c, d, a, b}} Proof of result A question was raised regarding the validity of the result of this function. You can graphically demonstrate that this function yields the correct result (as I understand it) for length 2,4 lists with this: ArrayPlot @ f[{Pink, Red}, {1, 2, 3, 4}] Pink always precedes Red The gray values are always in order No shuffles are missing No shuffles are duplicated I must conclude that the referenced paper is in error, or the original question diverges from the definition of "shuffle product" therein. Extension to multiple lists While it is possible to extend a two-list shuffle product to multiple lists using Fold it may be of interest to do it directly. This code is slow however and should not be used where performance matters. f2[in_, out___] :=
Join @@ ReplaceList[in, {x___, {a_, b___}, y___} :> f2[{x, {b}, y}, out, a]]
f2[{{} ..}, out__] := {{out}}
f2[{{1, 2}, {Cyan}, {LightRed, Pink, Red}}] // Transpose // ArrayPlot Alternative method Edit: I had a function g which used Permutations on a binary list to generate all the base orderings, but I did not fill these orderings efficiently. rasher used the same start but came up with a clever and fast way to fill those orderings. I am replacing this section of my answer with a refactored version of his code; credit to him for making the Permutations approach competitive. (If you are interested in my original, slow g see the edit history.) Here is a refactoring of rasher's shufflem function; I shall call mine shuffleW . Edit 2017 : Now significantly faster after moving or eliminating several Transpose operations. shuffleW[s1_, s2_] :=
Module[{p, tp, ord},
p = Permutations @ Join[1 & /@ s1, 0 & /@ s2]\[Transpose];
tp = BitXor[p, 1];
ord = Accumulate[p] p + (Accumulate[tp] + Length[s1]) tp;
Outer[Part, {Join[s1, s2]}, ord, 1][[1]]\[Transpose]
]
shuffleW[{a, b}, {c, d}] {{a, b, c, d}, {a, c, b, d}, {a, c, d, b}, {c, a, b, d}, {c, a, d, b}, {c, d, a, b}} Timings Timings of these functions as well as Simon's shuffles and rasher's shufflem , performed in v10.1. I am also including rasher's unnamed but very fast penultimate Ordering method. I shall call it shuffleO and format it for readability. shuffleO[s1_, s2_] :=
With[{all = Join[s1, s2]},
Join[1 & /@ s1, 0 & /@ s2]
// Permutations
// Map[Ordering @ Ordering @ # &]
// Flatten
// all[[#]] &
// Partition[#, Length[all]] &
]
s1 = CharacterRange["a", "k"];
s2 = Range @ 11;
f[s1, s2] // Length // RepeatedTiming
shuffles[s1, s2] // Length // RepeatedTiming
shufflem[s1, s2] // Length // RepeatedTiming
shuffleO[s1, s2] // Length // RepeatedTiming
shuffleW[s1, s2] // Length // RepeatedTiming {2.6523, 705432}
{2.0618, 705432}
{1.455, 705432}
{0.78, 705432}
{0.759, 705432} rasher's methods are the fastest in this test.
I find my f the most readable as the mechanism of its action is directly visible. Take your pick. :-) Disparate list lengths Yi Wang posted a nice clean method that has some interesting properties. Specifically it is the best performing solution so far in the case of input lists of significantly disparate length, but they must be fed in the correct order or the performance is magnitudes worse. First in the symmetric test above: Fold[insertElem, {{s2, 0}}, s1][[All, 1]] // Length // RepeatedTiming {2.67, 705432} Now with disparate lists: s1 = Range[80];
s2 = {"a", "b", "c"};
Fold[insertElem, {{s2, 0}}, s1][[All, 1]] // Length // RepeatedTiming {6.25, 91881} Swap the lists and try again (so that insertElem is Folded over the shorter list): {s2, s1} = {s1, s2};
Fold[insertElem, {{s2, 0}}, s1][[All, 1]] // Length // RepeatedTiming {0.121, 91881} This is significantly faster than all the others (order makes little difference to these): f[s1, s2] // Length // RepeatedTiming
shuffles[s1, s2] // Length // RepeatedTiming
shufflem[s1, s2] // Length // RepeatedTiming
shuffleO[s1, s2] // Length // RepeatedTiming
shuffleW[s1, s2] // Length // RepeatedTiming {0.529, 91881}
{0.5637, 91881}
{0.562, 91881}
{0.4135, 91881}
{0.4356, 91881}
|
{
"source": [
"https://mathematica.stackexchange.com/questions/41614",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6583/"
]
}
|
41,706 |
Bug introduced in 7.0 or earlier and persisting through 11.3 In this simple code ListPlot[Table[Sin[x], {x, 0, Pi, .1}], PlotRange -> {0, 0.5},
Joined -> True, PlotMarkers -> Automatic, ClippingStyle -> None, Frame -> True] We can see that there are two PlotMarkers appear at the clipped boundary. But actually there are not points, so they should not exist. How can we remove them? I have already used ClippingStyle -> None . Update As Alexey Popkov pointed out, this is really a bug. If we play with this code data = {Table[{x, Sin[x]}, {x, 0, 1.05 Pi, .1}], Table[{x, Sin[2 x]}, {x, 0, 1.05 Pi, .1}]};
ListPlot[data, PlotRange -> {0, 0.5}, Joined -> True, PlotMarkers -> {Automatic, Medium}] Now, even the same plot marker will be used for all data sets at the clipped boundaries, both top and bottom.
|
ListPlot[Table[Sin[x], {x, 0, Pi, .1}], PlotRange -> {0, 0.5}, Joined ->
True, PlotMarkers -> Automatic, ClippingStyle -> False, Frame -> True]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/41706",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5943/"
]
}
|
41,711 |
When I am fitting data with a pointwise function using NonlinearModelFit , the produced FittedModel fails to calculate variances and errors. Consider a toy example: Clear[f, data];
data = {{1, 7.4}, {2, 1.9}, {3, 6.}};
f[1.] = 2. a + b;
f[2.] = 3. a/b;
f[3.] = 3. b/a + a;
fit = NonlinearModelFit[data, f[t], {a, b}, t, Method -> NMinimize] When I take fit["BestFitParameters"] it gives a correct result {a -> 2.19044, b -> 2.95013} . However, when I try to take fit["EstimatedVariance"] it throws exception, since values of a and b can not be substituted in fit["Function"] (that's my guess). I found the following obvious workaround: Clear[f, g, h];
f[1.] = 1; g[1.] = 0; h[1.] = 0;
f[2.] = 0; g[2.] = 1; h[2.] = 0;
f[3.] = 0; g[3.] = 0; h[3.] = 1;
fit =
NonlinearModelFit[data, (2 a + b) f[t] + 3 a/b g[t] + (3 b /a + a) h[t],
{a, b}, t, Method -> NMinimize] but it is not elegant at all. What is the best way to obtain a complete FittedModel using NonlinearModelFit with a pointwise functions?
|
ListPlot[Table[Sin[x], {x, 0, Pi, .1}], PlotRange -> {0, 0.5}, Joined ->
True, PlotMarkers -> Automatic, ClippingStyle -> False, Frame -> True]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/41711",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/8360/"
]
}
|
42,047 |
As the title says, I wonder if it is possible to calculate a Lebesgue integral in Mathematica , especially when the domain of integration is $\mathbb{R}^N$, or in other words multivatiate Lebesgue integration is of interest. As an example, one could take $f_0$ and $f_1$ as two different (possibly correlated) bi-variate Gaussian density functions and consider $$\int_{\frac{f_1}{f_0}>\tau}f_0\mbox{d}\mu=\int_{\Large\{x,y:\frac{f_1(x,y)}{f_0(x,y)}>\tau\Large\}}f_0(x,y)\mbox{d}x\mbox{d}y$$
for some known number $\tau$. If it is not possible can one manipulate the existent functions of Mathematica to get a method which can calcuate the Lebesgue integral. I am only interested in very fast numerical methods, no analytical results are needed. Note : Why am I asking such a question here? I checked google about it and found no answer I checked the Mathematica help and found no result I searched the keyword "Lebesgue" among the questions in mathematica.stackexchange.com but couldnt see any related answer I have no idea how I can do it in Mathematica
|
The answer is no , because of fundamental mathematical limitations which originate in set theory regarding countability (see e.g. Cantor's theorem ) - functions over a given set are more numerous than the set's (power) cardinality . Neither Mathematica nor any other system can integrate every function in an even much more restricted class; namely, Riemann integrable functions . All Riemann integrals are equal to Lebesgue integrals if the former are well defined. The class of functions which could be integrated over a domain in $\mathbb{R}^n$ in Mathematica is of "measure zero" in the class of Lebesgue integrable functions. More precisely, we need Baire categories to work with general topological concepts of the class of adequate functions. When we calculate a definite integral, we are going to think of NIntegrate rather than Integrate . Let's try to integrate a simple Lebesgue integrable function defined in $\mathbb{R}$: f[x_] /; x ∈ Rationals && 0 <= x <= 1 := 1
f[x_] /; ! (x ∈ Rationals) && 0 <= x <= 1 := 0
f[Sqrt[3]/2]
f[1/2] 0
1 but neither Integrate nor NIntegrate can calculate adequate integrals: Integrate[ f[x], {x, 0, 1}]
NIntegrate[ f[x], {x, 0, 1}] although we know it should be 0 .
Having said that, we can always supplement built-in integration rules with user-defined ones (see e.g. Why aren't these additions of integrals and summations equal? ) to expand a class of symbolically or numerically integrable functions - for this purpose Mathematica is most likely the best tool. While we could always remedy various problems algorithmically, we shouldn't expect that it could be done in full generality (e.g. because of the finite number of states of computers); otherwise, we should supplement the system's built-in integration rules with infinitely many user-defined rules to be able to integrate every Lebesgue integrable function. Next editions of Mathematica may involve more powerful symbolic capabilities for measure theory and Lebesgue integration problems, but we should realize that there will always be some limitations of the algorithmic approach to integration in the realm of integrable functions. Edit The above considerations concern the problem of integration of a possibly wide class of functions. However if one restricts to integration of bi-variate Gaussian density functions there is no need for distinction between Riemann and Lebesgue integrals. Since one needs fast numerical results I'd recommend taking a closer look at the NIntegrate Integration Strategies tutorial, especially at Crude Monte Carlo and Quasi Monte Carlo Strategies and Global Adaptive Monte Carlo and Quasi Monte Carlo Strategies sections. Let's define e.g. f1[x_, y_] := PDF[ BinormalDistribution[{1, 3/2}, {1/2, 3/5}, 1/3], {x, y}]
f2[x_, y_] := PDF[ BinormalDistribution[{4/3, 7/3}, {1, 2/3}, 2/5], {x, y}] and choose e.g. τ = 5 . An especially fast method would be e.g. Method -> "AdaptiveMonteCarlo" with Boole[ f1[x, y] > 5 f2[x, y]] - appropriate region selector. Instead of Boole we could use HeavisideTheta , e.g. HeavisideTheta[ f1[x, y] - 5 f2[x, y]] but in this case it appears to be fairly slower (see e.g. this for the case when it is much faster). Working with "AdaptiveMonteCarlo" , one should remember that the method provides a rather rough estimation of the result: NIntegrate[ f1[x, y] Boole[ f1[x, y] > 5 f2[x, y]], {x, -∞, ∞}, {y, -∞, ∞},
Method -> "AdaptiveMonteCarlo"] 0.370381 A slower but considerably more stable method would be Method -> "AdaptiveQuasiMonteCarlo" .
|
{
"source": [
"https://mathematica.stackexchange.com/questions/42047",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/4256/"
]
}
|
42,304 |
There are no issues trying to find the intersection points of two defined curves. f[x_] := 2 (x - 1) (x - 1.5) (x - .5) (x + .5) (x + 1) (x + 1.5);
g[x_] := 0.4 x - 0.4;
Solve[f[x] == g[x], x]
(*{{x -> -1.39849}, {x -> -1.20949}, {x -> -0.331841}, {x ->
0.426865}, {x -> 1.}, {x -> 1.51295}}*)
Manipulate[Plot[Evaluate[{f[x], g[x]}], {x, -1.5, 1.52},
Epilog -> {Red, PointSize[Large],
Point[{#, f[#]} & /@ (x /.
Solve[f[x] == g[x], x])]}], {a, -0.8, .5, .2}] When I try to perform the same but this time with an interpolation function I run into problems. points = Table[{x, f[x]}, {x, -1.5, 1.5, .25}];
if = Interpolation[points]; I can obtain the first intersection by using the following. Neither NSolve nor Solve will work with interpolation function. With Solve this will happen Solve[if[x] == g[x], x] Solve::inex: Solve was unable to solve the system with inexact coefficients or the system obtained by direct rationalization of inexact numbers present in the system. Since many of the methods used by Solve require exact input, providing Solve with an exact version of the system may help. >> With NSolve, you get a similar error. NSolve[if[x] == g[x], x, Reals] ( NSolve[InterpolatingFunction[{{-1.5,1.5}},<>][x]==-0.4+0.4 x,x,Reals] ) FindRoot[if[x] == g[x], {x, -1.5}]
(*{x -> -1.36794}*) Which makes this question different from marking points of intersections between two curves as the problem is specific when using InterpolationFunction What is the best way to find all intersection points between the range (-1.5 and 1.5)?
|
[I gave a similar response some time ago either in StackOverflow or MSE but now I cannot find it.] One way is to track the solution to the ODE that runs over the difference if[x]-g[x] . Use WhenEvent to record axis crossings. This will find all zeros that do not have multiplicity (that is, that cross transversally). Should also find any that are of odd multiplicity since they still cross the axis, albeit at slope of zero. Reap[
odsoln = NDSolve[{y'[x] == if'[x] - g'[x],
y[-1.5] == if[-1.5] - g[-1.5], WhenEvent[y[x] == 0, Sow[x]]},
y[x], {x, -1.5, 1.5}];][[2, 1]]
(* Out[21]= {-1.36793657661, -1.19575651253, -0.330396218898, \
0.425433482282, 0.999999923787} *)
Plot[y[x] /. odsoln[[1]], {x, -1.5, 1.5}]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/42304",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1096/"
]
}
|
42,493 |
How can I visualize the standard topological "rubber-sheet" construction of a torus, that is, morphing a square into a torus? How can I start or are there any examples in the Mathematica documentation respectively?
|
Edit I had some time so I've added full surface torus. Old code in edit history. DynamicModule[{x = 2., l = 100., x2 = 2., l2 = 100., grid, fast, slow},
Grid[{{
Graphics3D[{
Dynamic[Map[{Blue, Polygon[#[[{1, 2, 4, 3}]]]} &,
Join @@@ (Join @@ Partition[#, {2, 2}, 1])
]&[
ControlActive[fast[l, l2], slow[l, l2]]]
]
}, PlotRange -> {{-7, 7}, {-7, 7}, {-1, 2}}, ImageSize -> 600,
Axes -> True, BaseStyle -> 18]
,
Column[{
Slider[Dynamic[x, (l = 10.^#; x = #) &], {.0001, 2.}],
Slider[Dynamic[x2, (l2 = 10.^#; x2 = #) &], {.0001, 2.}] }]
}}]
,
Initialization :> (
grid[l_, l2_, n_, m_] := Outer[Compose,
Array[RotationTransform[# Pi/l2, {0, 0, 1.}, {0, -l2, 0}] &, n, {-1, 1}],
Array[RotationTransform[# Pi/l, {1., 0, 0}, {0, 2, l}][{0, 2, 0}] &, m, {-1, 1}],
1];
fast[l_, l2_] = grid[l, l2, 10, 10];
slow[l_, l2_] = grid[l, l2, 50, 25];
)] For < V.9 please switch Array to Table . This syntax for Array was introduced, silently, in V.9 . linespace equivalent in MMA
|
{
"source": [
"https://mathematica.stackexchange.com/questions/42493",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11993/"
]
}
|
42,793 |
I was thinking about the best way to include Mathematica code in a $\LaTeX$ document with a nice syntax highlighting. I have tried the packages listings and minted (with pygments ), which both claim to include Mathematica syntax highlighting. There is also a separate Mathematica lexer for pygments on github. Having looked at the output from these packages, I'm not entirely happy. I was hoping to obtain a result resembling as closely as possible Mathematica's native syntax highlighting or the highlighting used here on mma.SE (is that halirutan's prettify extension ?) My question is: What are users' preferred ways to include Mathematica code in $\LaTeX$ files that preserve syntax highlighting?
|
I too had a need for a better syntax highlighting engine for Mathematica that can be used in different formats (so the javascript plugin is ruled out), so I wrote a better lexer and highlighter for Pygments than the one that ships with pygments. From the README: It can currently lex and highlight: All builtin functions in the System` context including unicode symbols like π except those that use characters from the private unicode space (e.g. \[FormalA] ) User defined symbols, including those in a context. Comments, including multi line and nested. Strings, including multi line and escaped quotes. Patterns, slots (including named slots #name introduced in version 10) and slot sequences. Message names (e.g. the ivar in General::ivar ) Numbers including base notation (e.g. 8 ^^ 23 == 19 ) and scientific notation (e.g. 1 *^ 3 == 1000 ). Local variables in Block , With and Module . Installing it is as simple as executing pip install pygments-mathematica . Here's an example of using it in a $\LaTeX$ document: \documentclass{article}
\usepackage[english]{babel}
\usepackage{fontspec}
\setmonofont{Menlo}
\usepackage{minted}
\usemintedstyle{mathematica}
\begin{document}
\begin{minted}[linenos=true]{wolfram}
(* An example highlighting the features of
this Pygments plugin for Mathematica *)
lissajous::usage = "An example Lissajous curve.\n" <>
"Definition: f(t) = (sin(3t + Pi/2), sin(t))"
lissajous = {Sin[2^^11 # + 0.005`10 * 1*^2 * Pi], Sin[#]} &;
ParametricPlot[lissajous[t], {t, 0, 2 Pi}] /. x_Line :> {Dashed, x}
\end{minted}
\end{document} Assuming the file is called mma.tex , run xelatex --shell-escape mma.tex to generate a pdf that looks like this: The style mathematica is shipped with this plugin and if you'd like to change the colors, you can just update them in mathematica/style.py and then (re)install the plugin. If you like the default notebook colors, you can use the style mathematicanotebook .
|
{
"source": [
"https://mathematica.stackexchange.com/questions/42793",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9146/"
]
}
|
43,186 |
I thought I'd share some code in the form of a self-answered question, but other answers are of course welcome. Drop shadows are a familiar visual effect, giving the impression of a graphical element being raised above the screen. Simple specular highlights can also add a suggestion of depth. Here are examples of a flat graphic, the same graphic with a drop shadow, and with a shadow plus hightlights too. How can I create these effects in Mathematica ? Related questions: Torn edge paper effect for images How can I make a 2D line plot with a drop shadow under the line?
|
NB: the code is now on GitHub here . The code at the bottom of this answer defines a package, "shadow", with one public function, imaginatively named shadow , which creates drop shadows, and optionally adds simple highlights too. There are quite a few options and ways to use it, so it's probably easiest to describe its usage by examples. First I'll create some objects to play with, to avoid cluttering the examples with graphics code: plot = Plot[{Sin[x], Cos[x]}, {x, 0, 2 Pi}, PlotStyle -> Thick];
disks = Graphics[Table[{Hue[i], Disk[i {Sin[10 i], Cos[10 i]}, 0.4 i]}, {i, 0, 1, 1/20}]];
numbers = Pane[Style[N[Pi, 600], LineSpacing -> {0, 10}], 270];
image = ColorNegate@Blur[disks, 50];
parametric = ParametricPlot[(1 + 0.5 Sin[7 r]) {Sin[r + 0.3 Sin[14 r]],
Cos[r + 0.3 Sin[14 r]]}, {r, 0, 2 Pi}, PlotStyle -> Thickness[0.03],
Axes -> False, ImagePadding -> 10];
parametricframed = ParametricPlot[(1 + 0.6 Sin[6 r]) {Sin[r + 0.4 Sin[10 r]],
Cos[r + 0.4 Sin[10 r]]}, {r, 0, 2 Pi}, PlotStyle -> Thickness[0.01],
Frame -> True, GridLines -> Automatic]; The most basic usage is shadow[object, 0] . This simply applies a drop-shadow to the rectangular region containing the object: << "shadow`"
shadow[plot, 0] If a positive integer is supplied instead of 0, the rectangular region is given rounded corners, with the parameter specifying the radius. A third argument can also be used to specify an amount of padding to apply to the object. Here is the plot again, with rounded corners of 25 pixels radius, and 10 pixels of padding: shadow[plot, 25, 10] There are some options which give control over the basic properties of the shadow. "blur" - the amount of blur to apply to the shadow (larger values give a larger, softer shadow, making the object appear further above page). "offset" - the amount by which to offset the shadow in x and y. "color" - the colour of the shadow. This should be a colour directive or just a single number (which will be interpreted as a gray level). "outline" - whether to create an outline around the cut out region of the object - this should be True or False . The defaults are: {blur -> 10, offset -> {5, -5}, color -> 0.3, outline -> False} Here is an example using all those options - note that using colours other than gray tends to make the shadow look very un-shadow-like, but it's nice to have the option to change it anyway... shadow[plot, 25, 10, "blur" -> 25, "offset" -> {0, 0}, "color" -> Orange, "outline" -> True] A torn paper effect can be specified with a second argument like {"BR", 2.0} , in which the letters T,B,L, and R in the string determine which sides (top, bottom, left, right) of the object to tear, with the number controlling the amplitude of the tearing effect. (The amplitude can be omitted and defaults to a value of 1.) shadow[plot, {"TBLR", 0.5}, 20, "outline" -> True] The rounded/torn rectangle is actually a special case of the second argument of shadow . More generally this argument is a "mask" which defines a shape to be cut out of the "object". The mask is used to set an alpha channel on the object - where the mask is white the object is made completely transparent, and where the mask is black the object remains opaque. The shadow is also computed from the mask (by blurring it). Expressions given for mask and object are rasterized if they are not already images, so almost anything is valid input. The output is always an Image , with a size determined by the size of object plus sufficient padding to allow for the shadow. Here's a simple example - the mask is a black disk on a white background, so the result is to cut a disk shaped region from the object and put a shadow under it: shadow[numbers, Graphics[Disk[]]] If the mask is a graphics expression, any explicit colour directives are set to black before rasterizing. This allows you to use the same graphics expression for the object and the mask. Here the coloured disks are used as both object and mask - the effect is to put drop shadows on the graphics primitives: shadow[disks, disks] The mask can be an image too, so all sorts of shapes can be created. Here I've used a bit of image processing to create a mask from a blurred version of the plot: shadow[plot, Blur[plot, 5]~ImageAdjust~{0, 1, 200}, "outline" -> True] Because the shape is defined by transparency, the output of shadow can be nicely overlaid onto other graphics: Show[PieChart[{1, 1, 1, 1, 1, 1, 1}],
Epilog -> Inset[shadow[image, disks], {0, 0}, Automatic, 1.5]] There is one more option, "highlight" . This gives a slightly 3D effect by brightening the object on one side and darkening on the other, as if the light source casting the shadow was reflecting from a curved surface. The highlight is specified with two parameters {scale, intensity} , where scale controls the size of the effect in pixels and intensity controls the strength of the effect. If set to True , the highlight uses default values of {1, 1.5} . shadow[image, parametric, "highlight" -> True] If you just want to apply a block colour to the mask, a colour directive can be given for the object and it will automatically be converted into an image of that colour. In the example below the infinity symbol is coloured orange by specifying Orange as the object.
Note that I've converted the text to a filled curve graphics primitive - this is because graphics can be rasterized at any size with good quality, whereas text tends to give poor results if rasterized larger than its natural size. inf = Graphics@Cases[ImportString@ExportString[Style["\[Infinity]",
FontFamily -> "Calibri", Bold, FontSize -> 12], "PDF"], _FilledCurve, -1];
shadow[Orange, inf, "highlight" -> {3, 2}] One final thing to mention is that if the mask is a graphics expression, any frame, axes or gridlines will be composed into the final image without processing, this allows the creation of plots with a shadow applied to the primitives but retaining readable (non shadowed) axes. In most cases the proper alignment between graphics and axes should be maintained, e.g. in the example below the curve crosses the axes at the correct coordinates. Note that this process doesn't always work - it relies on Rasterize behaving in a predictable manner which it doesn't always do! shadow[Red, parametricframed, "highlight" -> True] That's it. I hope someone finds it useful. Here's the actual code: BeginPackage["shadow`"];
shadow::usage="shadow[object, mask, padding]";
Begin["`Private`"];
Options[shadow]={"blur"->10,"offset"->{5,-5},"color"->0.3,"outline"->False,"highlight"->False};
shadow[ob_,mask_,pad_Integer:0,OptionsPattern[]]:=
Module[{i,dims,m,b,x,y,padding,shad,shadcol,object,result,hi,bkg},
b=OptionValue["blur"];
{x,y}=OptionValue["offset"];
hi=OptionValue["highlight"];If[TrueQ[hi],hi={1,1.5}];
i=ImagePad[toimage[ob],pad,Padding->Automatic];
dims=ImageDimensions[i];
{m,bkg}=preprocessGraphicsMask[mask];
m=createMask[m,dims];
If[hi=!=False,i=highlight[i,m,{x,y},hi]];
If[OptionValue["outline"],i=outline[i,m]];
padding=b+(#-Min[#])&/@{{x,0},{y,0}};
shad=ImagePad[m,padding,Padding->Black]~Blur~b;
shadcol=colorimage[tocolor[OptionValue["color"]],ImageDimensions[shad]];
shad=SetAlphaChannel[shadcol,shad];
object=ImagePad[SetAlphaChannel[i,m],Reverse/@padding,Padding->RGBColor[0,0,0,0]];
result=ImageCompose[shad,object];
If[bkg=!=0,
result=ImageCompose[ImagePad[rastersize[bkg,dims],Reverse/@padding,Padding->Automatic],result]];
ImagePad[result,Clip[8-BorderDimensions[result,0],{-Infinity,0}],Padding->Automatic]]
anycolor=_GrayLevel|_Hue|_RGBColor|_CMYKColor;
tocolor[col_?NumberQ]:=tocolor[GrayLevel[col]]
tocolor[col:anycolor]:=ColorConvert[col,"RGB"]
tocolor[notcol_]:=Black
colorimage[col_,dims_]:=ImageResize[Image[{{{##}}}],dims]&@@col
toimage[ob:(_Image|_Graphics)]:=ob
toimage[ob:anycolor]:=colorimage[tocolor[ob],{360,360}]
toimage[ob_]:=Rasterize[ob]
preprocessGraphicsMask[mask:Graphics[prims_,opts__/;!FreeQ[{opts},Axes|Frame|GridLines]]]:=
{Show[mask,AxesStyle->Opacity[0],FrameStyle->Opacity[0],GridLinesStyle->Opacity[0],Background->None],Graphics[{},opts]}
preprocessGraphicsMask[mask_]:={mask,0}
createMask[mask_,dims_]:=ColorNegate[icreateMask[mask,dims]~ColorConvert~"Grayscale"]
icreateMask[mask_Image,dims_]:=resizeAR[mask,dims]
icreateMask[mask_Graphics,dims_]:=rastersize[blacken@mask,dims]
icreateMask[mask_,dims_]:=resizeAR[Rasterize[blacken@mask],dims]
icreateMask[r_Integer,{w_,h_}]:=Module[{rr=Floor@Min[2r,w-1,h-1]},
icreateMask[ColorNegate[Image[ConstantArray[1,{2h-2rr,2w-2rr}]]~ImagePad~rr~ImageConvolve~DiskMatrix[rr]],{w,h}]]
icreateMask[{s_String,amp_:1},dims_]:=tornpage[dims,s,amp]
(* equivalent to Rasterize[expr, ImageSize \[Rule] dims] but uses correct StyleSheet *)
rastersize[expr_,dims_]:=Rasterize[Show[expr,ImageSize->dims]]
resizeAR[x_,{w_,h_}]:=ImageCrop[ImageResize[x,{{w},{h}}],{w,h},Padding->Automatic]
blacken[g_]:=g/.anycolor->Black
tornpage[{w_,h_},edges_,amp_]:=
Module[{left,right,bottom,top,page},
left=If[StringFreeQ[edges,"L"],{{0,h},{0,0}},Reverse/@tear[h,amp]];
right=If[StringFreeQ[edges,"R"],{{w,0},{w,h}},Reverse[#+{0,w}]&/@tear[h,amp]];
bottom=If[StringFreeQ[edges,"B"],{{0,0},{w,0}},tear[w,amp]];
top=If[StringFreeQ[edges,"T"],{{w,h},{0,h}},(#+{0,h})&/@Reverse[tear[w,amp]]];
page=Graphics[Polygon[Join[bottom,right,top,left]],PlotRangePadding->0,ImagePadding->0,AspectRatio->h/w];
ImagePad[Rasterize[page,ImageSize->2+{w,h}],-1]]
tear[w_,amp_]:=Module[{a,b},
a=0.1Sqrt[w]amp Accumulate[RandomReal[{-1,1},{w}]];
b=a-Range[#1,#2,(#2-#1)/(w-1)]&[First@a,Last@a];
Transpose[{Range[0.,w,w/(w-1)],b}]]
highlight[i_,m_,{x_,y_},{s_,a_}]:=Module[{th,X,Y,hi},
th=If[x==0&&y==0,-Pi/4,ArcTan[x,y]];
{X,Y}=GaussianFilter[ImageData[m],{5s,s}, #]&/@{{1,0},{0,1}};
hi=a (Rescale[-X Sin[th]+Y Cos[th]]-0.5);
(* reduce shadows by 1/2 *)hi=hi(0.75 +0.25 Sign[hi]);
ImageAdd[i,Image[hi]]]
outline[i_,m_]:=ImageMultiply[i,ColorNegate[m~ImagePad~1~GradientFilter~1~ImagePad~-1]]
End[];
EndPackage[];
|
{
"source": [
"https://mathematica.stackexchange.com/questions/43186",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/862/"
]
}
|
43,381 |
Bug introduced in V6 and fixed in V11.3 The behavior indeed changed but now the documentation is clear about it. This code is inconsistent with the description from Power Programming with Mathematica : x = 5;
temp`x = 6;
Begin["temp`"]
{x, Global`x, temp`x} The result in my Mathematica session is {5, 5, 6} , but it's {6, 5, 6} in Section 8.1.1 of Power Programming with Mathematica (page 231 of the hardcopy or page 249 of the PDF).
|
This behaviour has changed since that book was published. I am writing this additional answer to make it clear how Mathematica 9 searches contexts for symbols and that even the current version 9 documentation is incorrect in describing this. How symbol lookup actually works When you enter a symbol name such as x , Mathematica will check if a symbol with this name already exists. It will first search the contexts from $ContextPath for x , one by one. If it doesn't find it there, it'll search the context from $Context for it. If it still doesn't find it, then it will create a new symbol named x in $Context . Thus $ContextPath controls where to look for symbols, while $Context controls where to create new symbols. Your observations are explained by these rules, noting that Begin will change $Context only but not $ContextPath . Note that BeginPackage will change both $Context and $ContextPath . Warning: the documentation contains an error in Mathematica versions older than 11.3. The $ContextPath documentation states that $ContextPath is a global variable that gives a list of contexts, after $Context , to search in trying to find a symbol that has been entered. In fact $ContextPath is searched before $Context in the current version. In old versions this was not the case , as the Wagner book describes. I don't know when the change happened. The Contexts tutorial does correctly state the order of search in the current version: Since $Context is searched after $ContextPath , you can think of it as having "." appended to the file search path.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/43381",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/12753/"
]
}
|
44,027 |
This may have been asked already, but I am considering making a game in Mathematica that two people can play. However, the issue with my idea is that the other player can't view the cards of the first player. Does anyone have any suggestions as to how I would tackle this problem? I would use two different computers, both with Mathematica installed.
|
MathLink can be used to establish communication between two kernels on different machines using TCP/IP. A basic example that illustrates the technique can be found in the Mathematica documentation. The basic sequence of events is like this: The server creates an endpoint using LinkCreate . The client connects using LinkConnect . When one side wants to send a message to the other, it uses LinkWrite . Each side periodically polls to see whether the other has sent a message using LinkReadyQ . If it returns True , then the message can be read using LinkRead . There are some gotchas to be aware of: A client should write a message to the server immediately after connecting. This establishes the actual connection. Also, I have experienced erratic behaviour from LinkConnectedQ and LinkReadyQ until that first message arrives at the server. UPDATE @OleksandrR. points out that the undocumented function LinkActivate will correct this issue. See his discussion here . On principle, I recommend reading incoming messages in held form using LinkRead[..., HoldComplete] and interpreting them using purpose-built code. If you simply evaluate the messages directly, it opens a window for a prankster (or worse) to execute arbitrary code on your machine. During the initial debugging stage, it is easy for communicating programs to get out of synch with one another, resulting in hangs. Sometimes the kernel resists aborting or interrupting expressions when engaged in blocking I/O. I have found it useful to create buttons somewhere in a notebook that will close or interrupt the active link when pressed. The button actions run with a separate kernel link and can sometimes be helpful to forcibly terminate a cranky connection. The link connection name needs to be communicated from the server to the client by some out-of-band means (e.g. the server player must tell/text/IM/email his chosen IP address and port to the client player). The following (v9) code implements a toy one-line chat application for a client/server pair. First, a function to create the chat panel used by both sides: chat[link_] :=
DynamicModule[{button, tick=0, valid=True, ready, connected, in="", out=""}
, button = Function[, Button[##, Enabled -> Dynamic[valid]], HoldAll]
; DynamicWrapper[
Grid[
{ {"Link name:", Dynamic@If[valid, link[[1]], "Closed"]}
, {"Tick:", Dynamic@tick}
, {"Message:", Dynamic[in]}
, {button["Send", LinkWrite[link, out]; out=""], InputField[Dynamic@out, String]}
, {button["Close", LinkClose[link]]}
}
]
, Refresh[
tick += 1
; {valid, connected, ready} =
Quiet @ Check[
{True, LinkConnectedQ @ link, LinkReadyQ @ link}
, {False, False, False}
]
; If[ready, in = LinkRead[link]]
, If[valid, UpdateInterval -> 0, None]
, TrackedSymbols :> {}
]
]
] Next, a function to create a server-side chat panel that listens on a specified IP port: chatServer[port_] :=
chat @ LinkCreate[ToString@port, LinkProtocol -> "TCPIP"] Finally, a function to create a client-side chat panel using the link name shown on the server's panel: chatClient[linkName_] :=
Module[{link = LinkConnect[linkName, LinkProtocol -> "TCPIP"]}
, LinkActivate[link]
; chat[link]
] The server creates his panel... ... then communicates the link name to the client by some means. Only the first part of the name needs to be communicated, [email protected] in the example. The client then uses this name to create his panel: The two can then communicate until one of them presses the Close button. The Tick field in this example simulates the background work performed by the game while waiting for communication from its peer. The code polls for messages as fast as possible, but this rate can be throttled by adjusting the UpdateInterval option to Refresh in chat . As is customary in these toy examples, little attempt is made to recover from error conditions.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/44027",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9457/"
]
}
|
44,099 |
I have Safari, Opera, Chrome, Firefox and IE installed how might a get a browser screen shot of a set of HTML code from inside Mathematica(for any of those browsers)? (Image is optional) The shortest/leanest/fastest approach(within reason) is ideal. For example: Waiting for a website to serve a screen shot is to long. The solution should be local. screenshot["<!doctype html><i>Italicized text</i>"]
screenshot["http://example.com"] Possible ideas: SWT , HTMLunit , http://watin.org/ , Selenium (fairly certain Selenium will work with right install and code).
|
Copying my answer from StackOverflow ( edit , now updated) ... If you are on Windows (with .NET), then you could use Mathematica's NETLink functionality in conjunction with the WebBrowser class to capture a screenshot of a web page: Needs["NETLink`"]
LoadNETType["System.Drawing.Imaging.ImageFormat", AllowShortContext -> False]
LoadNETType["System.Windows.Forms.WebBrowserReadyState", AllowShortContext -> False]
Options[dotNetBrowserScreenshot] = {Width -> 1024, Height -> Automatic};
dotNetBrowserScreenshot[uri_, OptionsPattern[]] :=
NETBlock @ Module[{browser, bitmap, tempFile, image, bounds}
, browser = NETNew["System.Windows.Forms.WebBrowser"]
; browser@Width = OptionValue[Width]
; browser@ScrollBarsEnabled = False
; browser@ScriptErrorsSuppressed = True
; browser@Navigate[uri]
; tempFile = Close@OpenWrite[]
; While[browser@ReadyState =!= System`Windows`Forms`WebBrowserReadyState`Complete
, Pause[0.05]
]
; bounds = browser@Document@Body@ClientRectangle
; browser@Height = OptionValue[Height] /. Automatic -> bounds@Height
; bitmap = NETNew["System.Drawing.Bitmap", browser@Width, browser@Height]
; browser@DrawToBitmap[bitmap, bounds]
; browser@Dispose[]
; bitmap@Save[tempFile, System`Drawing`Imaging`ImageFormat`Png]
; bitmap@Dispose[]
; image = Import[tempFile, "PNG"]
; DeleteFile[tempFile]
; image
] Sample use: The complete web page can be captured by using Height -> Automatic (which is the default). Note that the screenshot is being displayed at reduced magnification.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/44099",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/5615/"
]
}
|
44,151 |
I am trying to find the eigenvector of a $20000 \times 20000$ sparse matrix associated with the smallest eigenvalue. I realized that the smallest eigenvalue might be negative; for example, if the eigenvalues of the matrix are $ \{-3,1,2,5 \}$, I want to find the eigenvector associated with $-3$, not $1$ or $5$. Therefore the commands Eigensystem[matrix,-1] or Eigensystem[matrix,1] cannot be guaranteed to return the desired result. Furthermore, I don't have a lower bound estimate for the possible smallest eigenvalue. Is there a way to find the eigenvectors efficiently?
|
You can always modify the matrix so that the most negative eigenvalue is also the one with the largest absolute value, and hence corresponds to the first in the list returned by EigenVectors . An upper bound for the largest absolute value of any eigenvalue is the Hilbert-Schmidt norm . So you can rescale your matrix by subtracting this norm times the unit matrix. The eigenvalues will then be guaranteed to be no larger than zero, and therefore the most negative eigenvalue is the one with the largest absolute value. Here I do this with the random matrix d , nicely constructed by @belisarius to be symmetric: d = (# + Transpose@#) &@N@RandomInteger[{-10, 10}, {2000, 2000}];
nn = Norm[Flatten[d]];
Eigenvalues[d - nn IdentityMatrix[Dimensions[d]], 1] + nn
(* ==> {-762.081} *) As mentioned, you can then also get the eigenvector this way: ev = Eigenvectors[d - nn IdentityMatrix[Dimensions[d]], 1]; Update: version 10 In Mathematica version 10, there is another way to get the largest or smallest eigenvalues: using a Method setting with non-default "Criteria" : -Eigenvalues[-d, 1, Method -> {"Arnoldi", "Criteria" -> "RealPart"}]
(* ==> {-762.081} *) The Arnoldi method is used when only a few eigenvalues of a large matrix are needed. By default it uses the "Magnitude" as the criteria for finding these eigenvalues. But if you specify "RealPart" instead, the eigenvalue with the largest real part is found. Since we wanted the smallest real part, I simply reversed the sign of the matrix and undid that reversal in the end.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/44151",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/11013/"
]
}
|
44,355 |
I have a scanned image (binary-ized): Is there any way to reduce one of these curved lines (full or dotted) to a series of its coordinates (e.g., sampling interval of 0.01 on x-axis)? I've read some similar examples: Recovering data points from an image How do I find the coordinates of points in this image? How can I extract data points from a black and white image? Obtain Data points from a graph on an image without axes But my problem is slightly different: I have several curves in one image. I would like to isolate them one from another and make each curved selectable by a simple click so that, for the selected curve, a series of coordinates of its sampled points (e.g., interval of 0.01 on x-axis) can be returned. Like this:
|
I am not sure, if one can separate one curve out of the image. There is, however, another possibility to do what you want. It is possible to get the curve points out of the image. I am not sure, if I have already published here this answer. I checked but did not find it. Hence, I am publishing it. The task is fulfilled by a copyCurve function first described and then given below. The function copyCurve Description The function copyCurve enables one to get the coordinates of points of a curve plot found on an image, and memorizes them in a list entitled "listOfPoints" Parameters image is any image. It should have head Image . If it is a Graphics object, wrap it by the Image statement. The code uses specific Image properties during the rescaling. Controls The checkbox whiteLocatorRing defines, if locators are shown by a single color ring (unchecked), or with two rings, the outer having a color defined by the ColorSlider (see below), the inner one being white. This may be helpful, if working with a too dark image. size controls the size of the image. The default value is 450. This slider is used to adjust the size to enable the most comfortable work with the image plot. opacity controls the opacity of the line connecting the locators thickness controls the thickness of the double ring that forms each locator. lineThickness controls the thickness of the line connecting the locators color is the colour slider that controls the colour of the outer ring forming the locator and the line connecting them. The inner locator ring is always white or no white ring at all. radius controls the radius of the locators. InputFields The input fields should be supplied by the reference points x1 and x2 at the axis x, as well as y1 and y2 at the axis y. Buttons The buttons "Memorize scale X" and "Memorize scale Y" should be pressed after the first two locators are placed on the corresponding reference points (presumably, located at the x or y axes). Upon pressing the button "Memorize scale ..." the corresponding reference points are memorized. The button "Make list of the curve points" should be pressed at the end of the session. Upon its pressing the actual list of points representing those of the curve is assigned to the global variable listOfPoints . Operation sequence Execute the function Enter the reference points at the plot x axes into the input fields. Press Enter. Alt+Click on the point with x-coordinate x1. This brings up the first locator visible as a circle. Alt+Click (Command + Click for Mac OS X) on that with x2 which gives rise to the second locator. Adjust the locators, if necessary. Press the button "Memorize scale X". Enter the reference points at the plot y axes into the input fields. Press Enter. Move the two already existing locators to the points with the coordinates y1 and y2. Press the button "Memorize scale Y". Now the both scales are captured. Move the two already existing locators to the first two points of the curve to be captured. Alt+Click on other points of the curve. Each Alt+Click will generate an additional locator. Adjust locators, if necessary. To remove, press Alt+Click on unnecessary locators. Press the button "Make the list...". This assigns the captured list to the global variable listOfPoints . Done. The listOfPoints is a global variable. It can be addressed everywhere in the notebook. at work: pic = Import["http://i.stack.imgur.com/gQvOw.jpg"]
copyCurve[pic] The code Clear[copyCurve];
copyCurve[image_] :=
Manipulate[
DynamicModule[{pts = {}, x1 = Null, x2 = Null, y1 = Null,
y2 = Null, X1, X2, Y1, Y2, \[CapitalDelta]X, \[CapitalDelta]Y, g,
myRound},
myRound[x_] := Round[1000*x]/1000 // N;
(* Begins the column with all the content of the manipulate *)
Column[{
(* Begin LocatorPane*)
Dynamic@LocatorPane[Union[Dynamic[pts]],
Dynamic@
Show[{Image[image, ImageSize -> size],
Graphics[{color, AbsoluteThickness[lineThickness],
Opacity[opacity], Line[Union[pts]]}]
}], LocatorAutoCreate -> True,
(* Begin Locator appearance *)
Appearance -> If[whiteLocatorRing,
Graphics[{{color, AbsoluteThickness[thickness],
Circle[{0, 0}, radius + thickness/2]}, {White,
AbsoluteThickness[thickness], Circle[{0, 0}, radius]}},
ImageSize -> 10]
,
Graphics[{{color, AbsoluteThickness[thickness],
Circle[{0, 0}, radius + thickness/2]}},
ImageSize -> 10]](* End Locator appearance *)
],(* End LocatorPane*)
(* Begin of the block of InputFields *)
Row[{ Style["\!\(\*SubscriptBox[\(x\), \(1\)]\):"],
InputField[Dynamic[x1],
FieldHint -> "Type \!\(\*SubscriptBox[\(x\), \(1\)]\)",
FieldSize -> 7, FieldHintStyle -> {Red}],
Spacer[20], Style[" \!\(\*SubscriptBox[\(y\), \(1\)]\):"],
InputField[Dynamic[y1],
FieldHint -> "Type \!\(\*SubscriptBox[\(y\), \(1\)]\)",
FieldSize -> 7, FieldHintStyle -> {Red}]
}],
Row[{ Style["\!\(\*SubscriptBox[\(x\), \(2\)]\):"],
InputField[Dynamic[x2],
FieldHint -> "Type \!\(\*SubscriptBox[\(x\), \(2\)]\)",
FieldSize -> 7, FieldHintStyle -> {Red}],
Spacer[20], Style[" \!\(\*SubscriptBox[\(y\), \(2\)]\):"],
InputField[Dynamic[y2],
FieldHint ->
"Type \!\(\*SubscriptBox[\(y\), \(2\)]\)+Enter",
FieldSize -> 7, FieldHintStyle -> {Red}]
}],
(* End of the block of InputFields *)
(* Begin the buttons row *)
Row[{Spacer[15],
(* Begin button "Memorize scale X" *)
Button["Memorize scale X",
X1 = Min[Transpose[myRound /@ Union[pts]][[1]]];
X2 = Max[Transpose[myRound /@ Union[pts]][[1]]];
\[CapitalDelta]X = X2 - X1;
],(* End of button "Memorize scale X" *)
Spacer[70],
(* Begin button "Memorize scale Y" *)
Button["Memorize scale Y",
Y1 = Min[Transpose[myRound /@ Union[pts]][[2]]];
Y2 = Max[Transpose[myRound /@ Union[pts]][[2]]];
\[CapitalDelta]Y = Y2 - Y1;
](* End of button "Memorize scale Y" *)
}],(* End the buttons row *)
Spacer[0],
(* Begin button "Make the list of the curve's points" *)
Button[Style["Make the list of the curve's points" , Bold],
g[{a_, b_}] := {(x1*X2 - x2*X1)/\[CapitalDelta]X +
a/\[CapitalDelta]X*Abs[x2 - x1], (
y1*Y2 - y2*Y1)/\[CapitalDelta]Y +
b/\[CapitalDelta]Y*Abs[y2 - y1]};
Clear[listOfPoints];
listOfPoints = Map[myRound, Map[g, pts]]
](* End of button "Make the list..." *)
}, Alignment -> Center](*
End of column with all the content of the manipulate *)
],(* End of the DynamicModule *)
(* The massive of sliders begins *)
Column[{Row[{Control[{whiteLocatorRing, {True, False}}],
Spacer[50]}],
Row[{Spacer[32.35], Control[{{size, 450}, 300, 800}],
Spacer[38.5`], Control[{{opacity, 0.5}, 0, 1}]}],
Row[{Spacer[10.], Control[{{thickness, 1}, 0.5, 5}],
Spacer[13.65], Control[{{lineThickness, 1}, 0, 10}] }],
Row[{Spacer[22.8], Control[{color, Red}], Spacer[59.3],
Control[{{radius, 0.5}, 0, 3}]}]
}, Alignment -> Center],(* The massive of sliders ends *)
(* Definitions of sliders *)
ControlType -> {Checkbox, Slider, Slider, Slider, Slider,
ColorSlider, Slider},
ControlPlacement -> Top, SaveDefinitions -> True
]; Have fun.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/44355",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/13068/"
]
}
|
44,369 |
How is the default for the checkboxes created by CheckboxBar in a Manipulate set to be checked instead of unchecked? (The number of checkboxes may be variable.)
|
I am not sure, if one can separate one curve out of the image. There is, however, another possibility to do what you want. It is possible to get the curve points out of the image. I am not sure, if I have already published here this answer. I checked but did not find it. Hence, I am publishing it. The task is fulfilled by a copyCurve function first described and then given below. The function copyCurve Description The function copyCurve enables one to get the coordinates of points of a curve plot found on an image, and memorizes them in a list entitled "listOfPoints" Parameters image is any image. It should have head Image . If it is a Graphics object, wrap it by the Image statement. The code uses specific Image properties during the rescaling. Controls The checkbox whiteLocatorRing defines, if locators are shown by a single color ring (unchecked), or with two rings, the outer having a color defined by the ColorSlider (see below), the inner one being white. This may be helpful, if working with a too dark image. size controls the size of the image. The default value is 450. This slider is used to adjust the size to enable the most comfortable work with the image plot. opacity controls the opacity of the line connecting the locators thickness controls the thickness of the double ring that forms each locator. lineThickness controls the thickness of the line connecting the locators color is the colour slider that controls the colour of the outer ring forming the locator and the line connecting them. The inner locator ring is always white or no white ring at all. radius controls the radius of the locators. InputFields The input fields should be supplied by the reference points x1 and x2 at the axis x, as well as y1 and y2 at the axis y. Buttons The buttons "Memorize scale X" and "Memorize scale Y" should be pressed after the first two locators are placed on the corresponding reference points (presumably, located at the x or y axes). Upon pressing the button "Memorize scale ..." the corresponding reference points are memorized. The button "Make list of the curve points" should be pressed at the end of the session. Upon its pressing the actual list of points representing those of the curve is assigned to the global variable listOfPoints . Operation sequence Execute the function Enter the reference points at the plot x axes into the input fields. Press Enter. Alt+Click on the point with x-coordinate x1. This brings up the first locator visible as a circle. Alt+Click (Command + Click for Mac OS X) on that with x2 which gives rise to the second locator. Adjust the locators, if necessary. Press the button "Memorize scale X". Enter the reference points at the plot y axes into the input fields. Press Enter. Move the two already existing locators to the points with the coordinates y1 and y2. Press the button "Memorize scale Y". Now the both scales are captured. Move the two already existing locators to the first two points of the curve to be captured. Alt+Click on other points of the curve. Each Alt+Click will generate an additional locator. Adjust locators, if necessary. To remove, press Alt+Click on unnecessary locators. Press the button "Make the list...". This assigns the captured list to the global variable listOfPoints . Done. The listOfPoints is a global variable. It can be addressed everywhere in the notebook. at work: pic = Import["http://i.stack.imgur.com/gQvOw.jpg"]
copyCurve[pic] The code Clear[copyCurve];
copyCurve[image_] :=
Manipulate[
DynamicModule[{pts = {}, x1 = Null, x2 = Null, y1 = Null,
y2 = Null, X1, X2, Y1, Y2, \[CapitalDelta]X, \[CapitalDelta]Y, g,
myRound},
myRound[x_] := Round[1000*x]/1000 // N;
(* Begins the column with all the content of the manipulate *)
Column[{
(* Begin LocatorPane*)
Dynamic@LocatorPane[Union[Dynamic[pts]],
Dynamic@
Show[{Image[image, ImageSize -> size],
Graphics[{color, AbsoluteThickness[lineThickness],
Opacity[opacity], Line[Union[pts]]}]
}], LocatorAutoCreate -> True,
(* Begin Locator appearance *)
Appearance -> If[whiteLocatorRing,
Graphics[{{color, AbsoluteThickness[thickness],
Circle[{0, 0}, radius + thickness/2]}, {White,
AbsoluteThickness[thickness], Circle[{0, 0}, radius]}},
ImageSize -> 10]
,
Graphics[{{color, AbsoluteThickness[thickness],
Circle[{0, 0}, radius + thickness/2]}},
ImageSize -> 10]](* End Locator appearance *)
],(* End LocatorPane*)
(* Begin of the block of InputFields *)
Row[{ Style["\!\(\*SubscriptBox[\(x\), \(1\)]\):"],
InputField[Dynamic[x1],
FieldHint -> "Type \!\(\*SubscriptBox[\(x\), \(1\)]\)",
FieldSize -> 7, FieldHintStyle -> {Red}],
Spacer[20], Style[" \!\(\*SubscriptBox[\(y\), \(1\)]\):"],
InputField[Dynamic[y1],
FieldHint -> "Type \!\(\*SubscriptBox[\(y\), \(1\)]\)",
FieldSize -> 7, FieldHintStyle -> {Red}]
}],
Row[{ Style["\!\(\*SubscriptBox[\(x\), \(2\)]\):"],
InputField[Dynamic[x2],
FieldHint -> "Type \!\(\*SubscriptBox[\(x\), \(2\)]\)",
FieldSize -> 7, FieldHintStyle -> {Red}],
Spacer[20], Style[" \!\(\*SubscriptBox[\(y\), \(2\)]\):"],
InputField[Dynamic[y2],
FieldHint ->
"Type \!\(\*SubscriptBox[\(y\), \(2\)]\)+Enter",
FieldSize -> 7, FieldHintStyle -> {Red}]
}],
(* End of the block of InputFields *)
(* Begin the buttons row *)
Row[{Spacer[15],
(* Begin button "Memorize scale X" *)
Button["Memorize scale X",
X1 = Min[Transpose[myRound /@ Union[pts]][[1]]];
X2 = Max[Transpose[myRound /@ Union[pts]][[1]]];
\[CapitalDelta]X = X2 - X1;
],(* End of button "Memorize scale X" *)
Spacer[70],
(* Begin button "Memorize scale Y" *)
Button["Memorize scale Y",
Y1 = Min[Transpose[myRound /@ Union[pts]][[2]]];
Y2 = Max[Transpose[myRound /@ Union[pts]][[2]]];
\[CapitalDelta]Y = Y2 - Y1;
](* End of button "Memorize scale Y" *)
}],(* End the buttons row *)
Spacer[0],
(* Begin button "Make the list of the curve's points" *)
Button[Style["Make the list of the curve's points" , Bold],
g[{a_, b_}] := {(x1*X2 - x2*X1)/\[CapitalDelta]X +
a/\[CapitalDelta]X*Abs[x2 - x1], (
y1*Y2 - y2*Y1)/\[CapitalDelta]Y +
b/\[CapitalDelta]Y*Abs[y2 - y1]};
Clear[listOfPoints];
listOfPoints = Map[myRound, Map[g, pts]]
](* End of button "Make the list..." *)
}, Alignment -> Center](*
End of column with all the content of the manipulate *)
],(* End of the DynamicModule *)
(* The massive of sliders begins *)
Column[{Row[{Control[{whiteLocatorRing, {True, False}}],
Spacer[50]}],
Row[{Spacer[32.35], Control[{{size, 450}, 300, 800}],
Spacer[38.5`], Control[{{opacity, 0.5}, 0, 1}]}],
Row[{Spacer[10.], Control[{{thickness, 1}, 0.5, 5}],
Spacer[13.65], Control[{{lineThickness, 1}, 0, 10}] }],
Row[{Spacer[22.8], Control[{color, Red}], Spacer[59.3],
Control[{{radius, 0.5}, 0, 3}]}]
}, Alignment -> Center],(* The massive of sliders ends *)
(* Definitions of sliders *)
ControlType -> {Checkbox, Slider, Slider, Slider, Slider,
ColorSlider, Slider},
ControlPlacement -> Top, SaveDefinitions -> True
]; Have fun.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/44369",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1063/"
]
}
|
44,767 |
Say I have the function $f(x) = x \tanh(\pi x) \log (x^2 +a^2)$ where $a$ is some positive real number. Then it seems to be me that Mathematica when given such a Log[] function implicitly puts a branch-cut along the positive imaginary axis starting at $x = ia$. Now if I ask Mathematica to integrate $f(x)$ along some semicircle in the upper half plane parametized as say, $x = A e^{i\phi}$ ($A>a$) for $0 \leq \phi \leq \pi$, then is Mathematica 's answer trustworthy? Like did a large $A$ expansion (Series about $A=\infty$) and found that $xf(x)$ (that would practically be the integrand when converted into a $\phi$ integral), this function asymptotes as, $e^{2i\phi} \log(e^{2i\phi})A^2 + 2A^2 \log(A) + a^2$ (+ terms which go to zero as $A$ goes to infinity). Now on this asymptotic form the $\phi$ is integrable from $0$ to $\pi$ giving a finite answer. So relying on this Mathematica result can I say that this integral therefore diverges in the large $A$ limit as $ \text{(number)} A^2 + \text{(number)} A^2 \log(A)$ ? Like for example I chose $a=2$ and it seems to me that on using "NIntegrate" Mathematica says that the integral of this function on a circle centered at $2i$ goes to zero as the radius goes to 0. Is this correct? Thinking analytically this seems to be right...
|
The standard built-in logarithm function is defined for complex variables as follows: Log[z] = Log[Abs[z]] + I Arg[z] The location of the branch cut is simply caused by the convention that polar angles of z are assumed to be in the range $-\pi$ to $\pi$. This same branch cut is also part of the definition of the built-in Arg function. Here is a different logarithm function called simply (lower-case) log to which you can supply a polar angle $\sigma$ at which the branch cut is going to be: Clear[arg, log];
arg[z_, σ_: - Pi] := Arg[z Exp[-I (σ + Pi)]] + σ + Pi;
log[z_, σ_: - Pi] := Log[Abs[z]] + I arg[z, σ] The first argument is the same as in the usual Log function. The second argument is optional, and if it's omitted then the new function agrees with its built-in counterpart. The default branch cut of the phase angle arg is $\sigma = -\pi$. To illustrate these branch cut locations, I defined a "convenience function" that plots a function of the complex variable z in a square of side length 6 around the origin: plot[f_] := Module[
{fn = f /. z -> x + I y},
Show[
ContourPlot[
Im[fn],
{x, -3, 3}, {y, -3, 3},
ContourShading -> Automatic,
ExclusionsStyle -> Red
],
ContourPlot[
Re[fn],
{x, -3, 3}, {y, -3, 3},
ContourShading -> False,
ContourStyle -> Blue,
ExclusionsStyle -> Red
],
FrameLabel -> {"Re(z)", "Im(z)"},
Background -> Lighter[Orange],
PlotRangePadding -> 0,
PlotLabel ->
Framed[Grid[{{Style["-", Bold, Blue],
"Real part"}, {Style["-", Bold, Gray], "Imaginary part"}},
Alignment -> Left], FrameStyle -> None, Background -> White,
RoundingRadius -> 5],
ImageSize -> 300
]
] For example, see the location of the branch cuts ( red ) rotate from the default to a non-standard direction: GraphicsRow[{plot[Log[z]],plot[log[z,π/4]]}] But now look at your function, with a = 1 because that constant is irrelevant: plot[z Tanh[π z] Log[z^2 + 1]] Here, the default choice of branch cut of the Log function leads to vertical branch cuts in the complex plane. This means the upper half plane is not a safe place to be integrating in... Depending on your needs, you could try to change the branch cut location to something else by using the log function with an appropriate choice for $\sigma$. Here is where the freedom of choice in the function log comes in. Try this: plot[z Tanh[π z] log[z^2 + 1, 0]] And as you can see, the branch cuts are now in a different position, no longer cutting through the middle of your integration domain. Edit: consequences for integration The question states that an integral along a semicircle in the upper half plane is to be performed, and the integrand now could be one of these two functions, corresponding to the default branch cut and the rotated branch cut shown in the previous image. Here I define them as functions: f[z_] := z Tanh[π z] Log[z^2 + 1];
g[z_] := z Tanh[π z] log[z^2 + 1, 0] The question further asks whether the result of the integration is "trustworthy." The answer is yes, but you have to know what exactly you're asking Mathematica to do. Therefore, I'll add some different plots just to clarify what I already said above. Pick a radius for your integration contour: r = 6.2; This is chosen to be not too large so as to obscure things, but also to avoid hitting one of the singularities of the Tanh functions which appear at regular intervals along the imaginary axis. Now plot the two functions versus the polar angle in the interval corresponding to the upper half plane, and look at the numerical integrals of the two: Plot[Evaluate[{Re[#], Im[#]} &@f[r Exp[I ϕ]]], {ϕ,
0, Pi}] NIntegrate[f[r Exp[I ϕ]], {ϕ, 0, Pi}]
(* ==> 20.271 - 3.55271*10^-15 I *) This integral is perfectly allowable, but since it goes over the branch cut, you probably get something you didn't expect: in this case, a vanishing real part due to the cancelation of the area under the magneta, discontinuous curve. Mathematica doesn't produce a warning because isolated discontinuities are integrable. So is this result "trustworthy"? Sure. Do you want it? That's up to you. Compare this to the function I suggested earlier: Plot[Evaluate[{Re[#],Im[#]}&@g[r Exp[I ϕ]]],{ϕ,0,π}] NIntegrate[g[r Exp[I ϕ]], {ϕ, 0, Pi}]
(* ==> 58.2644 + 37.6991 I *) Now you're integrating over a continuous function, and that's true for any given r as long as it avoids the isolated singularities. This result is also "trustworthy." Unfortunately, I can't tell from the question if this is what's needed. In any case, since the asymptotic behavior of both functions is divergent at large r (which answers the other question in the post), the integral along a semicircle would have to be done at finite radius. From the comment I am guessing that the goal is somehow to apply Cauchy's theorem, which is perfectly OK, although in this problem it doesn't yield any benefit. Nevertheless, if this is the goal then you definitely have to avoid crossing branch cuts with the integration contour. So which of the cuts is a better choice in this situation? The answer is: g[z] , because even though the branch cut now extends along the real axis, you can certainly draw a closed contour that completes the semicircle by hugging the cuts from above. When doing this, you also end up having to calculate the integral over an infinitesimal circle around the branch point at $z = i$. By doing a series expansion of the factors around $z = i$ you can see that the integrand goes to zero and hence the integral is also zero. This answers the last question (which is not related to the choice of branch cuts). Edit 2 Just for fun, here is how the branch cuts of the different logarithm functions evolve into each other as I change the parameter $\sigma$: frames = Table[
plot[z Tanh[Pi z] log[z^2 + 1, σ]], {σ,
0, Pi, Pi/16}];
ListAnimate[Join[Reverse[frames], frames], AnimationRepetitions -> 1] The GIF was actually created with: Export["cuts.gif",Join[Reverse[frames],frames],
ImageResolution>72,AnimationRepetitions->Infinity,"DisplayDurations"->.1]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/44767",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/3065/"
]
}
|
45,410 |
I'd like to create transparent graphs like the following from P1095, Calculus 6th Ed, by James Stewart. Can Mathematica accomplish this? By "transparent," I mean the ability to see the interior, intersection, boundaries etc. preferrably with dashed hidden lines. Would someone please explain how to do this for a function like \begin{cases} (4 - z^2) = x^2 + y^2, 2 \le z \le 4 \\
x^2 + y^2 = 4, -2 \le z \le 2 \end{cases} http://reference.wolfram.com/mathematica/howto/AddTransparencyToPlots.html doesn't appear to be very helpful in that respect.
|
Update: This function has been updated to compatible with version 12.x and made available on Wolfram Function Repository as ResourceFunction["Graphics3DSketch"] : https://resources.wolframcloud.com/FunctionRepository/resources/Graphics3DSketch Yes we can. The following DashedGraphics3D[ ] function is designed to convert ordinary Graphics3D object to the "line-drawing" style raster image. Clear[DashedGraphics3D]
DashedGraphics3D::optx =
"Invalid options for Graphics3D are omitted: `1`.";
Off[OptionValue::nodef];
Options[DashedGraphics3D] = {ViewAngle -> 0.4,
ViewPoint -> {3, -1, 0.5}, ViewVertical -> {0, 0, 1},
ImageSize -> 800};
DashedGraphics3D[basegraph_, effectFunction_: Identity,
opts : OptionsPattern[]] /; !
MatchQ[Flatten[{effectFunction}], {(Rule | RuleDelayed)[__] ..}] :=
Module[{basegraphClean = basegraph /. (Lighting -> _):>Sequence[], exceptopts, fullopts, frontlayer, dashedlayer, borderlayer,
face3DPrimitives = {Cuboid, Cone, Cylinder, Sphere, Tube,
BSplineSurface}
},
exceptopts = FilterRules[{opts}, Except[Options[Graphics3D]]];
If[exceptopts =!= {},
Message[DashedGraphics3D::optx, exceptopts]
];
fullopts =
Join[FilterRules[Options[DashedGraphics3D], Except[#]], #] &@
FilterRules[{opts}, Options[Graphics3D]];
frontlayer = Show[
basegraphClean /. Line[pts__] :> {Thick, Line[pts]} /.
h_[pts___] /; MemberQ[face3DPrimitives, h]
:> {EdgeForm[{Thick}], h[pts]},
fullopts,
Lighting -> {{"Ambient", White}}
] // Rasterize;
dashedlayer = Show[
basegraphClean /.
{Polygon[__] :> {}, Line[pts__] :> {Dashed, Line[pts]}} /.
h_[pts___] /; MemberQ[face3DPrimitives, h]
:> {FaceForm[], EdgeForm[{Dashed}], h[pts]},
fullopts
] // Rasterize;
borderlayer = Show[basegraphClean /. RGBColor[__] :> Black,
ViewAngle -> (1 - .001) OptionValue[ViewAngle],
Lighting -> {{"Ambient", Black}},
fullopts,
Axes -> False, Boxed -> False
] // Rasterize // GradientFilter[#, 1] & // ImageAdjust;
ImageSubtract[frontlayer, dashedlayer] // effectFunction //
ImageAdd[frontlayer // ColorNegate, #] & //
ImageAdd[#, borderlayer] & //
ColorNegate // ImageCrop
] Usage: DashedGraphics3D[ ] has three kinds of arguments. The basegraph is the Graphics3D[ ] you want to convert. The effectFunction is an optional argument, which when used will perform the corresponding image effect to the hidden part. The opts are options intended for internal Graphics3D[ ] , which are mainly used to determine the posture of the final output. When omitted, it takes values as defined by Options[DashedGraphics3D] . Example: graph1 = Show[{
SphericalPlot3D[
1, {θ, 1/5 1.2 π, π/2}, {ϕ, 0, 1.8 π},
PlotStyle -> White,
PlotPoints -> 50, Mesh -> None, BoundaryStyle -> Black],
SphericalPlot3D[
1, {θ, 0, π/5}, {ϕ, π/4, 2.1 π},
PlotStyle -> FaceForm[Lighter[Blue, .9], GrayLevel[.9]],
PlotPoints -> 50, Mesh -> None, BoundaryStyle -> Black],
Graphics3D[{FaceForm[Lighter[Pink, .8], GrayLevel[.8]],
Cylinder[{{0, 0, 0}, {0, 0, .8 Cos[π/5]}}, Sin[π/5]]}]
},
PlotRange -> 1.2 {{-1, 1}, {-1, 1}, {0, 1}},
AxesOrigin -> {0, 0, 0}, Boxed -> False,
SphericalRegion -> True];
DashedGraphics3D[graph1] DashedGraphics3D[graph1, Lighting -> "Neutral"] Sidenote: The hidden border of the cylinder's side-wall can not be extracted by the "shadow" method (described below) used in DashedGraphics3D[ ] , so ParametricPlot3D[ ] -akin functions are needed instead of simply Cylinder[ ] . graph2 = ParametricPlot3D[
{u Cos[v], u Sin[v], Im[(u Exp[I v]^5)^(1/5)]},
{u, 0, 2}, {v, 0, 2 π},
PlotPoints -> 20, Mesh -> {2, 5}, MeshStyle -> Red, Boxed -> False,
BoundaryStyle -> Black, ExclusionsStyle -> {None, Black}];
DashedGraphics3D[graph2] Add an oil-painting effect: DashedGraphics3D[graph2,
ImageAdjust[ImageEffect[Blur[#, 3], {"OilPainting", 3}]] &
] As for OP's example: graph3 = Show[{
ContourPlot3D[(4 - z)^2 == x^2 + y^2, {x, -3, 3}, {y, -3, 3}, {z, 2, 4},
Mesh -> None, BoundaryStyle -> Black, PlotPoints -> 20],
ContourPlot3D[x^2 + y^2 == 4, {x, -3, 3}, {y, -3, 3}, {z, -2, 2},
Mesh -> None, BoundaryStyle -> Black]
},
PlotRange -> {{-3, 3}, {-3, 3}, {-2, 4}}]
DashedGraphics3D[graph3, ViewAngle -> .6, ViewPoint -> {3, 2, 1}] Explanation: Take graph1 as example. The frontlayer generates a solid style graphic using {"Ambient", White} lighting, where every object supposed to be hidden are all invisible: The dashedlayer does the opposite to the frontlayer . It sets all faces transparent, and all edges and lines Dashed : Apparently, subtracting frontlayer from dashedlayer , we can extract the hidden part with dashed-style (on which effectFunction is applied.), then we add it back to frontlayer : Now the only missed part is the outline contour. We solve this problem by first using {"Ambient", Black} lighting to generate the shadow of the whole graphics, then using GradientFilter to extract the outline, which is the borderlayer : Combine frontlayer , dashedlayer and borderlayer properly, we get our final result.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/45410",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/-1/"
]
}
|
45,417 |
I would like to try to recreate something similar to Paolo Čerić's torus animation : I have isolated the moving surface torus section from this Wolfram Demonstration by Kevin Sonnanburg: t = s; s = .001; θ = 0; Manipulate[
Show[{ParametricPlot3D[{Cos[u] (3 + Cos[t]), Sin[u] (3 + Cos[t]),
Sin[t]}, {u, Cos[θ] s - .5 + a,
Cos[θ] s + .5 + a}, {t, Sin[θ] s - .5 + b,
Sin[θ] s + .5 + b}, PlotPoints -> 4, PlotStyle -> Red,
PerformanceGoal -> "Quality", PlotPoints -> 6, Axes -> None,
Boxed -> False, Mesh -> None, PlotRange -> 4],
ParametricPlot3D[{Cos[
a + v Cos[θ]] (3 + Cos[b + v Sin[θ]]),
Sin[a + v Cos[θ]] (3 + Cos[b + v Sin[θ]]),
Sin[b + v Sin[θ]]}, {v, 0, s}, PlotPoints -> 20]},
PlotRange -> 4, ImageSize -> {200, 200}, ViewAngle -> π/10],
{{a, π, "shift X"}, 0, 6 π},
{{b, π, "shift Y"}, 0, 6 π},
AutorunSequencing -> {2, 3, 4}, SaveDefinitions -> True] I have tried to apply a texture to the section, and extend it over the whole torus, but I haven't made as much progress as I'd hoped.
|
Let's get a black torus: torus = First@ParametricPlot3D[{Cos[u] (3 + Cos[t]), Sin[u] (3 + Cos[t]), Sin[t]},
{u, 0, 2 Pi}, {t, 0, 2 Pi},
PlotStyle -> Black, Mesh -> None, PlotPoints -> 10] and now, this is a way to go: DynamicModule[{d1 = 0, d2 = 0},
Column[{
Graphics3D[{
torus,
Red, Dynamic[Riffle[
Point /@ Array[
{Cos[#] (3. + 1.01 Cos[#2]), Sin[#] (3. + 1.01 Cos[#2]), Sin[#2]} &,
{65, 15},
{{0 + d2/10, 2. Pi + d2/10}, {0. + d2, 2 Pi + d2}}]
, {Yellow, Pink, LightBlue}
]]
}
, ImageSize -> 500, Background -> Black, Boxed -> False]
,
Slider[Dynamic@d2, {0, 2. Pi, .01}]
}]] Not perfect but I don't have time now for more efficient approach :/. p.s. Array works this way on version 9. Use Table / Range for older versions.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/45417",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/9923/"
]
}
|
45,502 |
I have looked around here, and i am sure this has been answered, but i don't understand it. The thing is, I have taken a introductory signal processing course, and we had to use Mathematica, and i had no previous experience in Mathematica, so this made a lot of things hard for me. Now i need to understand how to visually present the spectral content of a sampled signal. So i try something simple, sampls = Table[Sin[n*(2 \[Pi])/1000*4], {n, 0, 2000}]; where we can assume that the sampling period is 1/1000s and we have a sinus with a frequency of 4 Hz. This signal is sampled for 2 seconds, meaning we get 8 periods of the signal. Now my naive attempt is to do this (as i saw something like this in some example somewhere): ListLinePlot[Abs[FourierDCT[sampls]], PlotRange -> {{0, 100}, {0, 30}}] Now i end up with this: which i can't make any sense out of... What does it mean? My dream is to be able to plot frequency on the x-axis and amplitude on the y-axis, so that i could present the teacher with a nice narrow peak with height 1 right above 4 on such a plot. My mathematical knowledge is rather weak, i'm sorry to say, so be gentle with me and explain as concrete as possible. This is not primarily a mathematics course.
|
This is how I would do this. Define frequencies and sampling rate precisely. Then use Periodogram because it takes SampleRate as an option and rescales frequency axis automatically. Read up Docs on Periodogram - see examples there. data = Table[{t, Sin[2 Pi 697 t] + Sin[2 Pi 1209 t]}, {t, 0., 0.1,
1/8000.}];
ListLinePlot[data, AspectRatio -> 1/4, Mesh -> All,
MeshStyle -> Directive[PointSize[Small], Red], Frame -> True]
Periodogram[data[[All, 2]], SampleRate -> 8000, Frame -> True,
GridLines -> {{697, 1209}, None},
FrameTicks -> {{All, All}, {{697, 1209}, All}},
GridLinesStyle -> Directive[Red, Dashed], AspectRatio -> 1/4] Your case specifically is also very simple - sampling rate 1 - or Automatic - and frequency max at 4/1000: sampls = Table[Sin[n*(2 \[Pi])/1000*4], {n, 0, 2000}];
Periodogram[sampls, Frame -> True, GridLines -> {{4/1000.}, None},
GridLinesStyle -> Directive[Red, Dashed],
PlotRange -> {{0, .05}, All}]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/45502",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/10563/"
]
}
|
45,519 |
I have some data of type {{x1, y1, f1}, {x2, y2, f2}, ...} and want to do ListContourPlot . However, there is a problem that the data f is not smooth enough and has small errors. Here is a toy example illustrating the problem: data = Flatten[
Table[{i (1 + RandomReal[0.1]), j (1 + RandomReal[0.1]),
i + j}, {i, 0, 100}, {j, 0, 100}], 1];
ListContourPlot[data, Contours -> {80, 120}, ContourShading -> None] I would need to smooth the lines in the above curve, to get something like Any ideas to get this kind of smoothed plot? Thanks! And here is the figure from real data (which is too large to paste here), which I need to smooth: I find this thread InterpolationOrder for ContourPlot related. But I was unable to get the method work in my case because of (I guess) different input. Note added: Thanks a lot for the answers! Those answers works great for the toy example, but for the real data I still cannot get smooth lines so far (edit: so far means before the great guys update their answers ^_^. Now it worked great). Here is my data and plotting function, just in case you would like to give a try. I will also investigate why those interesting methods fail to work when I apply it to data... https://www.dropbox.com/s/2pgobgrhbo42f4v/contourData.dat data = << "contourData.dat";
ListContourPlot[data, Contours -> {2.30, 6.18},
ContourShading -> None]
|
N.B. Your actual data calls for a more sophisticated approach than the quick hack in my original answer, so I've replaced it with a much better and quite general solution. There are two things that make your actual data harder to work with than the toy example. First, it is highly irregular and nonuniformly distributed: ListPlot[Most /@ data, AspectRatio -> 1] and second, it has an awful aspect ratio: ListPlot[Most /@ data, AspectRatio -> Automatic] If your $x$ and $y$ axes aren't actually spatial coordinates but represent independent quantities with different units, you would do well to rescale the data so that, say, the variances along both axes are equal: sd = StandardDeviation[data];
{scalex, scaley} = 1/Most[sd];
scaledData = {scalex, scaley, 1} # & /@ data; Now to smooth an arbitrary nonlinear function described by noisy samples at irregularly scattered locations, I believe a local regression (LOESS) model is appropriate. In fact, LOESS is a generally useful thing so it's worthwhile to have an implementation available in Mathematica, and since it's pretty simple to implement, I went ahead and did it. My implementation follows Cleveland and Devlin's 1988 paper , i.e. local quadratic regression with tricube weights, except their $q$ is my $k$. (* precompute spatial data structure because we'll be needing nearest neighbours a lot *)
nearest = Nearest[scaledData /. {x_, y_, z_} :> ({x, y} -> {x, y, z})];
(* local quadratic regression with k neighbours around point (x, y) *)
loess[nearest_, k_][x_, y_] := Module[{n, d, w, f},
n = nearest[{x, y}, k];
d = EuclideanDistance[{x, y}, Most[#]] & /@ n;
d = d/Max[d];
w = (1 - d^3)^3;
f = LinearModelFit[n, {u, v, u^2, v^2, u v}, {u, v}, Weights -> w];
f[x, y]] Now we can plot the contours of the regression function, scaling the coordinates back to the original data: fit = loess[nearest, 100];
{{xmin, xmax}, {ymin, ymax}, {zmin, zmax}} = {Min[#], Max[#]} & /@ Transpose[data];
ContourPlot[fit[scalex x, scaley y], {x, xmin, xmax}, {y, ymin, ymax},
Contours -> {2.30, 6.18}, ContourShading -> None] Seems to work pretty well.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/45519",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7253/"
]
}
|
45,647 |
Sorry I am not sure if I got anything wrong with this version of Mathematica and Mac OS X i am running. But every time I export a 3D graph, to png or tiff, I lost the view angle, view vector viewpoint information immediately. To let you know what I meant, here is a simple code: I typed: x = RevolutionPlot3D[Sqrt[((t/5)^2 - 1)*2], {t, 5, 20}] And I got a plot out[1]= Then I manually rotate the plot so that it looks better, for example like this: Ok, now, I used Export to export it to png: Export["test.png", %]; What I got is pathetically, the un-rotated png plot!: This is driving me crazy and dead.. I also tried to set Viewpoint and view vector, stuff to the code, it doesn't work for me either. I also tried Export["test.png",x] too, no luck. I understand I could easily right-click to save, But I need a background-none option to make the graph transparent.. Can any one confirm (this bug?) or i am doing something stupidly wrong? I checked the documentation and googled for 1 hour, nothing found. So the question is, how can I export the graph as it is shown on the notebook (if I can not, then what's the point of allowing us to rotate it..)
|
What is stored in variable x is different from rotated object you have in output cell. You rotated - so you changed the properties. Many ways to do this - so in addition to comments' methods... 1) In-Export rotation 2) Seeing options Export["test.png", Show[x, opts]]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/45647",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/6542/"
]
}
|
45,829 |
I'm new to Mathematica, I've been learning by myself, and, being a Java developer for some time, it makes it hard to adapt. I've tried to solve a Reddit challenge , and I came up with this solution: str = "[can {and it(it (mix) up)} look silly]"
total = ""
str = StringTake[str, {2, -2}]
inix[strn_] :=
Min[StringPosition[strn, "["], StringPosition[strn, "{"],
StringPosition[strn, "("]];
finix[strn_] :=
Max[StringPosition[strn, "]"], StringPosition[strn, "}"],
StringPosition[strn, ")"]];
howmany[strn_] :=
Length[StringPosition[strn, "["]] +
Length[StringPosition[strn, "{"]] +
Length[StringPosition[strn, "("]];
brackets[x_, y_] :=
If[x != \[Infinity], (total =
StringTake[str, {1, x - 1}] <> " " <>
StringTake[str, {y + 1, -1}] <> " " <> total;
str = StringTake[str, {x + 1, y - 1}]) ,
(total = str <> " " <> total; str = "")];
Do[brackets[inix[str], finix[str]], {i, howmany[str] + 1}];
StringSplit[total, Whitespace]
StringJoin[Riffle[%, " "]] Is there a better solution? From seeing some Mathematica code, this looks to be terribly big code. I would want just some pointers on how to improve.
|
In this response, I will focus upon the programming paradigm change when moving from Java to Mathematica . I will emphasize two differences between the languages. The first concerns the "feel" of writing Mathematica code. The second is about how iteration is expressed. The "Feel" of Mathematica Java is a reasonably conventional programming language, designed to conform to the principle of "least surprise" for programmers who are coming to it from other mainstream languages. The boundary between the language proper and the runtime libraries is well-defined. Learning Java is often just a matter of trying to find where a preconceived piece of functionality resides in the standard library. By contrast, the symbolic nature of Mathematica blurs the line between language and library. From a strict computer science perspective, one could argue that the core language is very tiny indeed. It consists of a few data types, some term-rewriting machinery, and little else. However, it does not feel this way to use it. Instead, I would suggest that learning Mathematica is more akin to learning a natural language. There is endless vocabulary, obscure idioms, weird exceptions, and countless ways to express any given concept. For me, the act of writing Mathematica code sometimes feels more like writing prose (or perhaps even poetry). This is simultaneously Mathematica's greatest strength and its greatest weakness. On the one hand, it is flexible enough to express an algorithm in many differents styles, e.g. procedural, functional, query-based, language-based, etc. On the other hand, the computer sometimes acts like you've just read it a piece of poetry or prose :) My advice is to learn Mathematica as if you were learning a new natural language. Slowly, patiently. Ability grows with use. Tackle lots of small problems (like this question -- you've come to the right place in Mathematica StackExchange!). Practice expressing the same concept many different ways. Read lots of code. Read random pages from the voluminous documentation -- there are many, many gems hiding in there. Don't try to bite off the whole thing at once. Iteration Okay, enough of the warm and fuzzy stuff. Let's talk about code. If I had to pick just one difference between Java and Mathematica to talk about, it would be iteration. Whenever we want to operate on a collection of items in Java, our first thought is to operate upon each item individually within an explicit loop (ignoring Java 8 for the moment). Mathematica takes a different approach. The first choice in Mathematica is to operate upon the collection as a single unit using implicit iteration. For example, the Java loops: for (int i = 0; i < array.length; ++i) { result[i] = array[i] + 1; }
for (int i = 0; i < array.length; ++i) { result2[i] = someFunction(array[i]); } would have the following Mathematica equivalents: result = array + 1;
result2 = Map[someFunction, array]; The iteration is implicit. A big part of the study of Mathematica is about learning these higher-level functions that perform implicit iteration. Explicit iteration still happens in Mathematica , but it is not the first tool to reach for. It is almost always fruitful to seek an operator that will transform a collection in one fell swoop. You can get a feel for iteration in Mathematica from the Functional Operations tutorial in the documentation, but you'd be hard-pressed to find a better investment of your time than to read Mathematica Programming - an advanced introduction . One final point before we move on to the specific problem from the question. Mathematica has very few facilities to destructively alter large data structures. Any modification of, say, a list results in a copy of that list being generated. This is the Mathematica way, and one just has to embrace it. It is possible to write (often convoluted) code to minimize memory usage, but the first tool in the toolbox almost always involves lots of data structure copying. A common theme that you will find in the answers here on the Mathematica StackExchange is that the fastest algorithms frequently use the most memory. Don't fight it, unless there is no alternative. Memory is cheap. (ohh, the fading memory of C/C++ in my mind stirs restlessly :) The Problem, At Last As you can see from the many responses to this question, there are many ways to approach this problem. I dare say that they hardly scratch the surface of possible solutions. I will add another, but make no claim as to how it stacks up against other answers. This response is more concerned with the process of creating the solution. Mathematica is first and foremost an exploratory programming environment. Let's explore. The first thing we know for sure is that we will need to divide the string into pieces. Let's play: $string = "[can {and it(it (mix) up)} look silly]";
Characters[$string]
(* {[,c,a,n, ,{,a,n,d, ,i,t,(,i,t, ,(,m,i,x,), ,u,p,),}, ,l,o,o,k, ,s,i,l,l,y,]} *)
StringSplit[$string, Characters["{[()]}"]]
(* {can ,and it,it ,mix, up,, look silly} *)
$split = StringSplit[$string, RegularExpression["(?<=[(){}[\\]])|(?=[(){}[\\]])"]]
(* {[,can ,{,and it,(,it ,(,mix,), up,),}, look silly,]} *) That last one looks promising. Take no notice of the fact that I pulled that regex out of a hat -- this post is long enough! What we need to do is to scan for brackets and drop down a level when we see an opening one and pop back up when we see a closing one: $changes = Replace[$split, {"["|"{"|"("->-1, "]"|"}"|")"->1, _->0}, {1}]
(* {-1,0,-1,0,-1,0,-1,0,1,0,1,1,0,1} *) Those represent the level changes, but we are really more interested in the levels themselves. We need to keep a running total of the changes. It so happens that there is an operation for that: $levels = Accumulate @ $changes
(* {-1,-1,-2,-2,-3,-3,-4,-4,-3,-3,-2,-1,-1,0} *) Now we have the individual strings and their levels. We need to sort them by level. Here are a couple ways to do that. First, we could pair up each string with its level and then use SortBy : $pairs = Transpose[{$split, $levels}]
(* {{[,-1},{can ,-1},{{,-2},{and it,-2},{(,-3},{it ,-3},{(,-4},{mix,-4},{),-3},
{ up,-3},{),-2},{},-1},{ look silly,-1},{],0}} *)
$sorted = SortBy[$pairs, {Last}]
(* {{(,-4},{mix,-4},{(,-3},{it ,-3},{),-3},{ up,-3},{{,-2},{and it,-2},{),-2},
{[,-1},{can ,-1},{},-1},{ look silly,-1},{],0}} *) Here, the "natural language" behaviour of Mathematica crops up. We need the sort to be stable, that is, elements at the same level must stay in the original order. The way to achieve that is to say SortBy[$pairs, {Last}] instead of SortBy[$pairs, Last] . There is a logical explanation for this (see the documentation ), but it is far from obvious. This is an example of something one just picks up by experience and hard knocks. There is another way to perform this sort that is even less obvious, but is actually a fairly common idiom: $sorted = $split[[Ordering@$levels]]
(* {(,mix,(,it ,), up,{,and it,),[,can ,}, look silly,]} *) Ordering does not sort the list, but rather tells you the index of each element as it would appear in a sorted list. This is useful to sort one list based upon the contents of another. It eliminates the need to assemble an intermediate list of pairs first. (Although we are still assembling an intermediate list of indices. Memory. Cheap. Remember?). The list still contains all of the brackets. We need to remove those: $result = DeleteCases[$sorted, "{"|"["|"("|")"|"]"|"}"]
(* {mix,it , up,and it,can , look silly} *) We need to join the strings together: StringJoin @@ $result
(* mixit upand itcan look silly *) Hmm, we need to something about those spaces. Let's delete the excess: StringJoin @@ StringTrim @ $result
(* mixitupand itcanlook silly *) Oops, we need spaces between the strings. StringJoin @@ Riffle[StringTrim @ $result, " "]
(* mix it up and it can look silly *) Riffle ? Where did that come from? Alas, it is simply vocabulary that must be memorized. At last, we have the result. Let's pull it all together, keeping our favourites from the variations: decode[string_] :=
Module[{split, changes, levels, sorted, result}
, split = StringSplit[string, RegularExpression["(?<=[(){}[\\]])|(?=[(){}[\\]])"]]
; changes = Replace[split, {"["|"{"|"("->-1, "]"|"}"|")"->1, _->0}, {1}]
; levels = Accumulate @ changes
; sorted = split[[Ordering@levels]]
; result = DeleteCases[sorted, "{"|"["|"("|")"|"]"|"}"]
; StringJoin @@ Riffle[StringTrim @ result, " "]
]
decode["[can {and it(it (mix) up)} look silly]"]
(* mix it up and it can look silly *) If we are performing a one-off task, there is little need to search for alternative approaches as we have done above. The first approach we find is just fine, provided if gives us our result. But sometimes it takes a while to find an approach that performs well and/or is comprehensible enough to convince ourselves that it is correct. That is where the need to write, rewrite and rewrite again surfaces, just as when writing natural-language prose. Parting Tip The widespread mathematical ethic of terseness has taken hold in the Mathematica community. So we are just as likely to see the preceding function expressed without making the intermediate expressions explicit: decode2[string_] :=
StringSplit[string, RegularExpression["(?<=[(){}[\\]])|(?=[(){}[\\]])"]] //
StringJoin @@ Riffle[
StringTrim @ DeleteCases[
#[[Ordering @ Accumulate @ Replace[#, {"["|"{"|"("->-1, "]"|"}"|")"->1, _->0}, {1}]]]
, "{"|"["|"("|")"|"]"|"}"
]
, " "
] &
decode2["[can {and it(it (mix) up)} look silly]"]
(* mix it up and it can look silly *) There it is, fully-grown, armed and armoured as if sprung directly from Zeus' head. Time to post to StackExchange! We might consider such an approach to show little mercy to the reader, who must reverse-engineer what is happening. This is a common problem in expressive high-level languages. Terse expression can sometimes give few cues for understanding. With experience, it becomes easier to read such expressions. In the meantime (and beyond), a little helper function can help wade through code like this: P[x___, l_] := (Print[Row[{x, l}, " "]]; l) This function prints out its arguments, returning the last unchanged. It can be quickly inserted at various places in a pipeline to see what they return. For example: Module[{level = 0}
, P@StringCases["[can {and it(it (mix) up)} look silly]"
, { s:Characters["[{("] :> (--level; ##&[])
, s:Characters["]})"] :> (++level; ##&[])
, s:Except@Characters["[{()}] "].. :> {s, level}
}
]
] //
P@SortBy[#, {Last}]& //
#[[All, 1]]&
(*
{{can,-1},{and,-2},{it,-2},{it,-3},{mix,-4},{up,-3},{look,-1},{silly,-1}}
{{mix,-4},{it,-3},{up,-3},{and,-2},{it,-2},{can,-1},{look,-1},{silly,-1}}
{mix,it,up,and,it,can,look,silly}
*) Note the use of P before the StringCases and the Sort , causing their results to be shown. This technique is far more "low tech" than the debuggers in the Front-End and Workbench, but in the notebook interface it is quick and easy and often all that one needs. (And the attentive reader will have noticed that the code block was yet another approach to the problem, using a semi-imperative style. Assuming said attentive reader was not put to sleep half-way through this TL;DR :)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/45829",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/13425/"
]
}
|
46,238 |
I cannot understand the difference between Apply , Scan , and Map . I have tried to play with these functions using the codes below: f[x_] := x^2 Map[f, {{a, b}, c}] Output: {{a^2, b^2}, c^2} Apply[f, {{a, b}, c}] Output: f[{a, b}, c] Scan[f, {{a, b}, c}] There is no output for this one. The function of Map is understandable. But I cannot get the purpose of Apply and Scan . What are the differences between these three functions?
|
These three functions are similar (speaking commonly), and in some applications any of them could be used, yet they have very different special applications. Rudimentarily: Map wraps (sub)expressions in a given Head, and returns the modified input Apply replaces Heads in (sub)expressions, and returns the modified input Scan "visits" (sub)expressions, evaluates each of them, and returns Null (For each example below f should be undefined; start with ClearAll[f] .) Map Most basically Map works like this: f /@ head[1, 2, 3] (* shorthand for Map[f, head[1, 2, 3], {1}] *) head[f[1], f[2], f[3]] As with each of the functions under discussion it can operate at different levels: Map[f, {{1, 2}, {3, 4}}, {0}]
Map[f, {{1, 2}, {3, 4}}, {1}]
Map[f, {{1, 2}, {3, 4}}, {2}]
Map[f, {{1, 2}, {3, 4}}, {0, 2}] f[{{1, 2}, {3, 4}}]
{f[{1, 2}], f[{3, 4}]}
{{f[1], f[2]}, {f[3], f[4]}}
f[{f[{f[1], f[2]}], f[{f[3], f[4]}]}] Map is an additive process; it inserts additional heads into an expression at the specified levelspec and then evaluates it. If the expression is held nothing evaluates. (Held meaning the outermost Head has an Attribute such as HoldAll . Hold has this attribute. Do not confuse the Head with the Attribute.) Print /@ Hold[a[1, 2], b[3, 4]] Hold[Print[a[1, 2]], Print[b[3, 4]]] Apply Apply works like Map , except that instead of adding a Head it replaces an existing one, if a head exists at the specified level. Unlike Map it is frequently used at levelspec {0} with the short form @@ , which replaces the outermost head: f @@ head[1, 2, 3] (* short form of Apply[f, head[1, 2, 3], {0}] *) f[1, 2, 3] A second short form ( @@@ ) exists for levelspec {1} : f @@@ {{1, 2}, {3, 4}} {f[1, 2], f[3, 4]} If a sub-expression is atomic (has no operable Head) Apply does not modify it: f @@@ head[1, 2, x + y] head[1, 2, f[x, y]] Note that 1 and 2 are unmodified, while x + y (which has a FullForm of Plus[x, y] ) had its Head replaced. As with Map , Apply transforms an expression and then evaluates it in entirety; if it is held evaluation does not continue: Print @@@ Hold[a[1, 2], b[3, 4]] Hold[Print[1, 2], Print[3, 4]] One way to "release" this expression for evaluation is to replace Hold with something else, like List : List @@ Print @@@ Hold[a[1, 2], b[3, 4]] 12 34 {Null, Null} Note here that the elements 1 , 2 , and 3 , 4 are printed by Print , but since Print[. . .] itself evaluates to Null the output of the line is {Null, Null} . Scan Scan is also like Map , except that each individual expression which is wrapped in the specified head is evaluated outside of the main expression, and the main expression is never returned. If we Scan a function without side-effects over an expression we get nothing: Scan[f, head[1, 2, 3]] (This could also be written f ~Scan~ head[1, 2, 3] .) We do not even get an output line because the output is Null and Mathematica does not print a lone Null output line (by convention). If we use a function with side-effects, such as Print , we get a different result: Scan[Print, head[1, 2, 3]] 1 2 3 Crucially Scan will carry out its evaluation even when an expression is held because it only looks at the subexpressions: Print ~Scan~ Hold[a[1, 2], b[3, 4]] a[1,2] b[3,4] Its evaluation can also be interrupted because, unlike Map and Apply which transform the entire expression, then evaluate it, Scan works incrementally: (Print[#]; If[# > 2, Return[]]) & ~Scan~ {1, 2, 3, 4, 5} 1 2 3 Because Scan does not first duplicate and then modify the entire expression it may be more memory efficient than the use of Map or Apply , but it will still unpack packed arrays therefore if memory efficiency is a priority other methods may be preferred. Conclusion I hope these simple examples illustrate that these three functions, while closely related, have unique characteristics that differentiate their use, and each has powerful applications that the others do not. Recommended reading regarding performance of these and related functions: Two ways of map a function on the list: Which one is faster? Choose between `Apply` and `Map` Notes on atomic objects Not all expressions that have the appearance head[arguments] in FullForm are actually standard expressions in that form that can be manipulated with structural tools such as Apply . Instead they have a special internal format and they are merely displayed in the form head[arguments] . From the documentation on Atomic Objects : All expressions in Mathematica are ultimately made up from a small
number of basic or atomic types of objects. These objects have heads that are symbols that can be thought of as
"tagging" their types. The objects contain "raw data", which can
usually be accessed only by functions specific to the particular type
of object. You can extract the head of the object using Head, but you
cannot directly extract any of its other parts. Standard objects such as strings and integers are atomic, but so are other expressions that may not appear to be: list = {1, "test", 1/2, 2 + 3 I};
list // FullForm
AtomQ /@ list List[1, "test", Rational[1, 2], Complex[2, 3]]
{True, True, True, True} Also atomic are more complex structures such as SparseArray , Graph , BooleanFunction , and (in recent versions) Image . Atomic objects (or atoms) are handled differently from standard (compound) expression forms. Rational[1, 2] is atomic even though it appears otherwise. Even though 1 is formatted without an obvious head, Head will return Integer . (See Is there a summary of answers Head[] can give? for other examples.) Apply does not work in the "normal" way on atoms: new @@@ list {1, "test", 1/2, 2 + 3 I} Replace and kin often work on the apparent FullForm of atoms: Replace[list, head_[args__] :> {head, args}, {1}] {1, "test", {Rational, 1, 2}, {Complex, 2, 3}} Functions may be overloaded to handle atoms differently; e.g. many functions treat a SparseArray as they would the Normal form expression: new @@ SparseArray[{1, 2, 3}] new[1, 2, 3] (* not new[{1, 2, 3}] *) Handling may appear somewhat irregular even within functions; Part will "extract" (or return) the head of Rationa[1, 2] but not anything else: Part[1/2, 0] Rational Part[1/2, 1] Part::partd: Part specification (1/2)[[1]] is longer than depth of object. >> (1/2)[[1]] (Somewhat related, and perhaps of interest: Head and everything except Head? )
|
{
"source": [
"https://mathematica.stackexchange.com/questions/46238",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/1205/"
]
}
|
46,760 |
How can I download historical data from Yahoo ? Although Mathematica's FinancialData function uses Yahoo it could be useful to have more control on how to retrieve data from Yahoo's YQL. Edit Similarly how could I use Quandl ?
|
Here's a set of functions that allows to do this. The code uses many ideas found on this site and on other places on the web. It is a bit factorized already so it should be easily reusable. More on YQL and available tables here: https://developer.yahoo.com/yql https://github.com/yql Query test Edit : this API is great also and simple http://www.quandl.com/help/api You get usable data in MM and some basic data manipulation straight away using Import@"http://www.quandl.com/api/v1/datasets/WIKI/AAPL.csv?sort_order=asc&exclude_headers=true&rows=3&trim_start=2012-11-01&trim_end=2013-11-30&column=4&collapse=quarterly&transformation=rdiff" The work below is still useful in order to access other types of data than financial ones in YQL. Here are usage examples symbol="YHOO";
symbols={"YHOO","GE"};
startDate={2013,04,13};
endDate={2014,04,16};
GetYahooMultiQuote[symbol,startDate,endDate]
GetYahooMultiQuote[symbols,startDate,endDate,{"Adj_Close","High"}] Note that if you request too much data you won't be able to query too many symbols at the same time. But it's still quite practical to be able to get data for many symbols in only one request for a small historical time range. toYahooString[string_String]:="\""<>string<>"\"";
toYahooDate[date_List]:=DateString[date,{"Year", "-","Month","-","Day"}]//toYahooString;
toYahooList[list_List]:=StringJoin@@Riffle[toYahooString/@list,","];
toYahooUrl[sqlRequest_String]:=
Module[{urlRules},
urlRules={" "->"%20","\""->"%22","("->"%28",")"->"%29"};
StringReplace[
"http://query.yahooapis.com/v1/public/yql?env=store://datatables.org/alltableswithkeys&format=json&q="
<>sqlRequest
,
urlRules
]
];
toYahooRequest[sqlRequest_]:=sqlRequest//toYahooUrl//Import[#,"JSON"]&;
doAndParseYahooRequest[sqlRequest_,yahooResultField_,requiredFields_,nsymbols_]:=
Module[{jsonImport,quotes},
jsonImport=sqlRequest//toYahooRequest;
quotes=OptionValue[jsonImport,yahooResultField];
requiredFields/.quotes // Partition[#,Length@#/nsymbols]& // If[Length@#==1,First@#,#]&
];
possibleQuotes=Alternatives@@{"Adj_Close","Close","Date","High","Low","Open","Symbol","Volume"};
ClearAll@GetYahooMultiQuote;
GetYahooMultiQuote[symbols_,startDate_,endDate_,quote:(possibleQuotes|{possibleQuotes..}):"Adj_Close"]:=
Module[{symbols2=Flatten@{symbols},sqlRequest,sqlRequestModified},
sqlRequest="select * from yahoo.finance.historicaldata where symbol in (SYMBOLS) and startDate = START_DATE and endDate = END_DATE";
sqlRequestModified=
StringReplace[
sqlRequest
,
{"SYMBOLS"->toYahooList@symbols2,"START_DATE"->toYahooDate@startDate,"END_DATE"->toYahooDate@endDate}
];
doAndParseYahooRequest[sqlRequestModified,"query"->"results"->"quote",quote,Length@symbols2]
]; Edit For Quandl the following function is useful. It implements all the importing options described in the help http://www.quandl.com/help/api . It works for a single set or a multiset. It includes memoization also. (*"transformation=none|diff|rdiff|cumul|normalize"
"collapse=none|daily|weekly|monthly|quarterly|annual"
"sort_order=asc|desc"
"dataFormat=csv|json|xml"*)
ClearAll@GetQuandlData;
Options[GetQuandlData]={"Collapse"->"daily","Tansformation"->"none","Sort"->"asc","ExcludeHeaders"->True,"Column"->4,"DataFormat"->"csv","Token"->None};
GetQuandlData[ticker_,nData:({startDate_,endDate_}|rows_),opts:OptionsPattern[]]:= GetQuandlData[ticker,nData,opts]=
Module[{dataFormat,collapse,transformation,sort,url,excludeHeaders,column,token},
{dataFormat,collapse,transformation,sort,excludeHeaders,column,token}=
OptionValue[GetQuandlData,#]&/@{"DataFormat","Collapse","Tansformation","Sort","ExcludeHeaders","Column","Token"};
url="https://www.quandl.com/api/v1/"~~
If[ListQ@ticker,
"multisets."~~
dataFormat~~
"?columns="~~
StringJoin@@
Riffle[
MapThread[
#1~~"."~~#2&
,
{StringReplace[#,"/"->"."]&/@ticker,ToString/@If[ListQ@column,column,ConstantArray[column,Length@ticker]]}
]
,
","
]
,
"datasets/"~~
ticker~~
"."~~
dataFormat~~
"?"~~
If[column===All,
""
,
"column="~~
ToString@column
]
]~~
"&collapse="~~
collapse~~
If[ListQ@nData,
"&trim_start="~~
DateString[startDate,{"Year","-","Month","-","Day"}]~~
"&trim_end="~~
DateString[endDate,{"Year","-","Month","-","Day"}]
,
"&rows="~~
ToString@rows
]~~
"&sort_order="~~
sort~~
"&transformation="~~
transformation~~
"&exclude_headers="~~
ToString@excludeHeaders~~
If[token===None,
""
,
"&auth_token="~~
token
];
Import@url
];
GetQuandlData["YAHOO/INDEX_GSPC", {{2014, 08, 16}, {2014, 10, 16}}, "Tansformation"->"diff"]
GetQuandlData["YAHOO/INDEX_VIX",10,"Sort"->"desc"]
GetQuandlData[{"YAHOO/INDEX_GSPC", "YAHOO/INDEX_VIX"},10,"Sort"->"desc","Column"->{4,2}]
GetQuandlData[{"YAHOO/INDEX_GSPC", "YAHOO/INDEX_VIX"},10,"Sort"->"desc","Column"->4]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/46760",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/66/"
]
}
|
47,597 |
Surfing on the web, I came upon this cool GIF: Does any one know how to reproduce this in Mathematica ? I have some ideas myself, so I will try to answer this question as well.
|
Embedded cdf with music version. code at the bottom For full period, change max t to 200 , my gif is cut in half because for some reasons I couldn't upload whole. f[r_, t_] := Mod[-t (1 - r), 2. Pi];
dr = Pi /100.
Animate[Graphics[{
Table[{
AbsolutePointSize[10 # + 2 + 2 Unitize@Clip[f[#, t] - 5.5, {0, 1}]],
Blend[{Blend["Rainbow", #], White}, Clip[f[#, t] - 5.28, {0, 1}]],
Point[# {Cos@f[#, t], Sin@f[#, t]}]} &@i,
{i, 1 - dr, 0, -dr}],
White, Line[{{0, 0}, {2, 0}}]},
PlotRange -> 1.1, Background -> Black, ImageSize -> 300],
{t, 0, 100}, AnimationRate -> 5] more processor consuming but working smoothly - version with music: As Öskå has noticed, it may not work on Linux. It is not perfectly optimized, I just wonted to do this now and I hope I will have some time and motivation to improve it one day. DynamicModule[{t, f, dt, dr, sound, graf},
Dynamic[Refresh[
Column[{
graf,
Animator[Dynamic[t, (t = #; With[{sel = Select[sound, t - dt <= #[[1]] <= t &]},
If[Length[sel] != 0, EmitSound@Sound[SoundNote@sel[[1, 2]]]]]) &],
{0, 200, dt}, AnimationRunning->False, AnimationRate->4, DisplayAllSteps->True]
}],
None]],
Initialization :> (
dt = .2;
f[r_, t_] := Mod[-t (1 - r), 2 Pi];
t = 0;
dr = Pi /100;
graf = Graphics[{
Dynamic@Table[With[{fi = f[i, t]},
{
AbsolutePointSize[5 i + 2 + If[fi > 6., 3, 0]],
Blend[{Blend["Rainbow", i], White}, Clip[fi - 5.5, {0, 1}]],
Point[i {Cos@fi, Sin@fi}]}],
{i, 1 - dr, 0, -dr}],
White, Line[{{0, 0}, {2, 0}}]},
PlotRange -> 1.1, Background -> Black, ImageSize -> 300];
sound = Composition[
SortBy[#, First] &,
{#[[1, 2]], #[[;; , 1]]} & /@ # &,
GatherBy[#, #[[2]] &] &,
Flatten[#, 1] &
]@Table[
Thread[{(-i + 1)/dr, Range[0, 200, #] &@(2 Pi/(1 - i))}], {i,
1 - dr, 0, -dr}];
)
]
|
{
"source": [
"https://mathematica.stackexchange.com/questions/47597",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7520/"
]
}
|
47,917 |
I am wondering how I could determine the frequency of oscillations of a differential model equation? How could I find the frequency from this example given in Mathematica Documentation: s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1}, y, {x, 0, 30}]
Plot[Evaluate[y[x] /. s], {x, 0, 30}, PlotRange -> All] I am asking because I need to determine the frequency of one model term as a function of a the strength of a second model term, in a much more complicated model than described above.
|
I'd advocate taking differences between successive peaks and likewise troughs. These can be found by keeping track of when the derivative is zero. pts =
Reap[s = NDSolve[{y'[x] == y[x] Cos[x + y[x]], y[0] == 1,
WhenEvent[y'[x] == 0, Sow[x]]}, {y, y'}, {x, 0, 30}]][[2, 1]]
(* Out[290]= {0.448211158984, 4.6399193764, 7.44068279785, 10.953122261, \
13.8722260952, 17.2486864443, 20.2244048853, 23.5386505821, \
26.5478466115, 29.8261176372} *)
Plot[{Evaluate[y[x] /. s], Evaluate[y'[x] /. s]}, {x, 0, 30},
PlotRange -> All] diffs = Differences[pts, 1, 2]
(* Out[288]= {6.99247163887, 6.31320288463, 6.43154329733, \
6.29556418327, 6.35217879014, 6.28996413777, 6.32344172616, \
6.28746705515} *)
Mean[diffs]
(* Out[289]= 6.41072921417 *) Noticing that the first might be an outlier, one might choose to discard it. Mean[Rest[diffs]]
(* Out[291]= 6.32762315349 *)
|
{
"source": [
"https://mathematica.stackexchange.com/questions/47917",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/7163/"
]
}
|
48,059 |
Sadly, I am a completely newbie. I am studying Physics and in our theoretical physics class we got the task to solve the double pendulum using Mathematica . We just got the program, but no introduction how to use it. So I am trying to animate the parametric plot. Any ideas? sol = NDSolve[{
2*phi1''[t] + phi2''[t]*Cos[phi1[t] - phi2[t]] +
phi2'[t]^(2)*Sin[phi1[t] - phi2[t]] + 2*9.81*Sin[phi1[t]] ==
phi2''[t] + phi1''[t]*Cos[phi1[t] - phi2[t]] -
phi1'[t]^(2)*Sin[phi1[t] - phi2[t]] + 9.81*Sin[phi2[t]] == 0,
phi1[0] == Pi/2, phi2[0] == Pi, phi1'[0] == 0, phi2'[0] == 0},
{phi1[t], phi2[t], t}, {t, 0, 10}]
Plot[{phi1[t], phi2[t]} /. sol, {t, 0, 10}]
x1[t] := Evaluate[Sin[phi1[t]] /. sol]
y1[t] := Evaluate[-Cos[phi1[t]] /. sol]
x2[t] := Evaluate[Sin[phi1[t]] + Sin[phi2[t]] /. sol]
y2[t] := Evaluate[-(Cos[phi1[t]] + Cos[phi2[t]]) /. sol]
ParametricPlot[Evaluate[{{x1[t], y1[t]}, {x2[t], y2[t]}} /. sol], {t, 0, 10}]
|
After correcting the syntax errors in the original code, the actual question can be addressed: How to display the four variables x1[t]...y2[t] as an animation in a way that conveys their meaning? The basic idea is to use ListAnimate on a list of frames that I define below: Clear[phi1, phi2, t];
sol = First[
NDSolve[{2*phi1''[t] + phi2''[t]*Cos[phi1[t] - phi2[t]] +
phi2'[t]^(2)*Sin[phi1[t] - phi2[t]] + 2*9.81*Sin[phi1[t]] == 0,
phi2''[t] + phi1''[t]*Cos[phi1[t] - phi2[t]] -
phi1'[t]^(2)*Sin[phi1[t] - phi2[t]] + 9.81*Sin[phi2[t]] == 0,
phi1[0] == Pi/2, phi2[0] == Pi, phi1'[0] == 0,
phi2'[0] == 0}, {phi1[t], phi2[t]}, {t, 0, 10}]];
x1[t_] := Evaluate[Sin[phi1[t]] /. sol]
y1[t_] := Evaluate[-Cos[phi1[t]] /. sol]
x2[t_] := Evaluate[Sin[phi1[t]] + Sin[phi2[t]] /. sol]
y2[t_] := Evaluate[-(Cos[phi1[t]] + Cos[phi2[t]]) /. sol]
frames = Table[
Graphics[{Gray, Thick,
Line[{{0, 0}, {x1[t], y1[t]}, {x2[t], y2[t]}}], Darker[Blue],
Disk[{0, 0}, .1], Darker[Red], Disk[{x1[t], y1[t]}, .1],
Disk[{x2[t], y2[t]}, .1]},
PlotRange -> {{-2.5, 2.5}, {-2.5, 2.5}}],
{t, 0, 10, .1}];
ListAnimate[frames] The list frames is generated in a Table where the time t is incremented in steps of .1 through the interval of the NDSolve solution. The drawing depicts the two xy coordinates as red disks, connected to each other and to the origin (the pivot) by gray lines. These are the rigid rods connecting the masses. In terms of code, I changed the definition of sol to remove one level of List so that the resulting definition of the coordinate functions doesn't end up returning lists, but numbers. These coordinate definitions should also have a t_ instead of x1[t] etc. to be consistent with the meaning of the := ( SetDelayed ) in their definition (alternatively one could also have done those definitions in a simpler way without := ). Edit: more general solution To get more out of this animation, it may be of interest to change the simulation so that it can handle different masses, and different pendulum lengths. But this means you need to understand how the differential equation must be modified. For many constrained mechanics problems, including the double pendulum, the Lagrange formalism is the most efficient way to set up the equations of motion. Mathematica has a VariationalMethods package that helps to automate most of the steps. This is extremely useful for solving mechanics problems because it lets you focus on the physics while taking over the mathematical work of getting from the physics to the equations of motion. Here is how it works. The following few lines contain all the steps from defining the variables to establishing and then solving the equations of motion, with arbitrary parameters for the pendulum geometry. Here s1 , s2 are the lengths of the two rods connecting the masses m1 , m2 . Most of the following equations can be done entirely in terms of the vectorial positions r1 and r2 without thinking about their components too much. The actual variables we solve for are ϕ1, ϕ2 . To show the effect of doubling one of the masses and halving one of the pendulum rods, I then set those variables before calling NDSolve : Needs["VariationalMethods`"]
Clear[s1, s2, ϕ1, ϕ2, t, g, m1, m2];
variables = {ϕ1[t], ϕ2[t]};
r1 = s1 {Sin[ϕ1[t]], -Cos[ϕ1[t]]};
r2 = r1 + s2 {Sin[ϕ2[t]], -Cos[ϕ2[t]]};
lagrangian =
m1/2 D[r1, t].D[r1, t] + m2/2 D[r2, t].D[r2, t] -
g {0, 1}.(m1 r1 + m2 r2);
eqs = EulerEquations[lagrangian, variables, t];
s1 = 1;
s2 = 1/2;
m1 = 2;
m2 = 1;
g = 9.81;
tMax = 10;
initial = {ϕ1[0] == Pi/2, ϕ2[0] == Pi,
ϕ1'[0] == Pi/2, ϕ2'[0] == 0};
sol = First[NDSolve[Join[eqs, initial], variables, {t, 0, tMax}]];
nFrames = 100;
frames = Table[Graphics[{Gray, Thick,
Line[{{0, 0}, r1, r2}],
Darker[Blue], Disk[{0, 0}, .1],
Darker[Red], Disk[r1, m1/10], Disk[r2, m2/10]} /. sol,
PlotRange -> {{-2.5, 2.5}, {-2.5, 2.5}},
Background -> Lighter[Cyan]],
{t, tMax/nFrames, tMax, tMax/nFrames}];
ListAnimate[frames] Note that the differential equations we're solving are never written down by hand anywhere. They are automatically generated by EulerEquations . Edit As requested in the comment, the solution above can also be re-used to plot a trace of the trajectory together with the pendulum graphic: traceFrames =
Map[ParametricPlot[r2 /. sol, {t, 0, #},
PlotStyle -> Directive[Thick, Lighter[Purple]],
PlotPoints -> Floor[(2 nFrames #)/tMax],
PlotRange -> {{-2.5, 2.5}, {-2.5, 2.5}},
Background -> Lighter[Cyan]] &,
Range[tMax/nFrames, tMax, tMax/nFrames]];
ListAnimate[MapThread[Show, {traceFrames, frames}]] Here I re-use the list of frames from above and Show it together with a new list traceFrames in which the ParametricPlot of the end point r2 is shown up to the intermediate time corresponding to the instants used in frame . Since ParametricPlot uses interpolation, we have to make sure that the plots for long times don't lose details, by increasing the number of PlotPoints with time.
|
{
"source": [
"https://mathematica.stackexchange.com/questions/48059",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/14439/"
]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.