How to work out or calculate this circuit?
The way it works is this.. when a positive voltage relative to DGND is applied to X1-1, then current flows through the LED in the PC817 opto-isolator. It illuminates the phototransistor and causes current to flow through the transistor if a voltage is applied. Typically IN0 will have something like a pullup resistor to some voltage relative to GND, so if that current is high enough, the voltage at IN0 will look more like a "low" than a "high". 

When a negative voltage is applied to X1-1, the diode D2 shunts the LED and keeps the reverse voltage across it from getting too high. No light is emitted under those conditions. If no voltage is applied to X1-1, again no current flows. 

When current is flowing through the LED, R4 shunts some of the current away. R5 determines the amount of total current that flows for a given input voltage. Let's suppose a nominal current of 20mA through the LED will guarantee that IN0 is "low", regardless of PC817 variations from unit-to-unit, with temperature, or as it ages and gradually grows "weaker". Suppose further that our input voltage is 12VDC, and we would like to assure reliable contact operation by passing a current of 50mA through the contacts. 

From the datasheet, we know that the forward voltage of the LED is 1.2V at 20mA, so the value of R5 should be (12V-1.2V)/0.05A = 216 ohms, so 220 Ohms might be a good choice. 

The value of R4 can be found from (1.2V/0.03A) = 40 ohms, so 39 ohms might be a reasonable standard value to choose. 

Let me emphasize that this is just an example, the choice of the resistors R4 and R5 is dependent on two sets of requirements, neither of which are stated. 

The 1N400x is non-critical.