I have an expression which contains a bunch of strings and some complex valued numeric factors in front. A couple of summands might look like this:

someResult = 
    I (I + Sqrt[3]) *
    ("C4cD_uuuu_g5.p001.d000_g5.p011.d000_g5.p110.d000_g5.p100.d000" -
     "C4cD_uuuu_g5.p001.d000_g5.p100.d000_g5.p110.d000_g5.p011.d000" -
     "C4cD_uuuu_g5.p110.d000_g5.p011.d000_g5.p001.d000_g5.p100.d000" +
     "C4cD_uuuu_g5.p110.d000_g5.p100.d000_g5.p001.d000_g5.p011.d000" +

In general there will be many more terms and different factors up front.

I would like to convert this into an association which maps the strings to complex factors, in this case it would look like this:

<|"C4cD_uuuu_g5.p001.d000_g5.p011.d000_g5.p110.d000_g5.p100.d000" ->
  I (I + Sqrt[3]),

Once I have this in that form I can export it as a CSV file which has the string as the first colum and N @ Re @ Value and N @ Im @ Value as second and third column.

When I try to use ReplaceAll to match the strings with a_ * str_String and turn them into association keys vand values, not all of them are detected properly. I have tried to use the linearity of the association values and just did this:

FullSimplify[someResult] /. {str_String :> Association[str -> 1]}

But then I got this result, which is also not exactly what I want:

I (I + Sqrt[3]) (
    <|"C4cD_uuuu_g5.p001.d000_g5.p011.d000_g5.p110.d000_g5.p100.d000" -> 1|> +
    <|"C4cD_uuuu_g5.p001.d000_g5.p100.d000_g5.p110.d000_g5.p011.d000" -> -1|> +
    <|"C4cD_uuuu_g5.p110.d000_g5.p011.d000_g5.p001.d000_g5.p100.d000" -> -1|> +
    <|"C4cD_uuuu_g5.p110.d000_g5.p100.d000_g5.p001.d000_g5.p011.d000" -> 1|> +
    <|"C4cV_uuuu_g5.p.d000_g5.p011.d000_g5.p001.d000_g5.p110.d000" -> 1|>)

Additionally there were warnings about keys occuring twice and so on.

Is there some way to just distribute the factors onto the strings, but not split up the real and imaginary parts of the factors into two summands?


1 Answer 1

keys = Union@Cases[someResult, _String, Infinity];

AssociationMap[Coefficient[someResult, #, 1] &] @ keys

enter image description here

KeyValueMap[Flatten@{#, N@ReIm@#2} &, %] // ExportString[#, "CSV"] &

enter image description here

  • $\begingroup$ I now have the problem that in one case this expression is of length 600 and this gets pretty slow. I noticed that adding a Distribute makes it go from not finishing within 30 minutes to being done pretty instantly. $\endgroup$ Commented Oct 10, 2019 at 11:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.